mirror of
https://github.com/db9979/tidefront.git
synced 2026-12-06 12:54:09 +01:00
Merge Aufholhilfe: Baugutschrift, Startpaket ab Tag 8; Balance v1.27; Entscheidungen Teil 5
This commit is contained in:
commit
fc36fd91fc
29 files changed
+1021
-17
No files matched your search
@@ -0,0 +1,46 @@
|
||||
// Aufholhilfe: Baugutschrift unter der Ressourcenleiste und im Bauhof (Betrag, Herkunft, Erklärung), Kosten im
|
||||
// Gebäudeblatt verrechnet; Ausbau mit leerem Lager allein aus der Gutschrift.
|
||||
import { expect, expectNoHorizontalOverflow, test } from "./fixtures.ts";
|
||||
import { readState, updateState } from "./game.ts";
|
||||
|
||||
test("Baugutschrift: sichtbar in Leiste und Bauhof, verrechnet in den Baukosten, bezahlt den Ausbau", async ({ page, player, seed }) => {
|
||||
await updateState(seed.sql, player.baseId, (s) => {
|
||||
s.resources = { stahl: 0, treibstoff: 0, elektronik: 0, proviant: 0 };
|
||||
s.resUpdatedAt = Date.now();
|
||||
s.catchUp = { credit: 5000, bonus: 0.5, ratio: 0.2, active: true, lastAtMs: Date.now(), earned: 0, pack: 5000 };
|
||||
});
|
||||
await page.goto("/");
|
||||
|
||||
// Ressourcenleiste: schmale Zeile mit Betrag und Herkunft.
|
||||
const strip = page.getByTestId("gutschrift-leiste");
|
||||
await expect(strip).toContainText("Baugutschrift 5.000");
|
||||
await expect(strip).toContainText("Aufholhilfe +50 %");
|
||||
await expectNoHorizontalOverflow(page, "Basis mit Baugutschrift");
|
||||
|
||||
// Bauhof: Betrag, Herkunft, Erklärblatt.
|
||||
const line = page.getByTestId("gutschrift-bauhof");
|
||||
await expect(line).toContainText("Baugutschrift");
|
||||
await expect(line).toContainText("Herkunft: Aufholhilfe (mit Startpaket)");
|
||||
await line.click();
|
||||
const info = page.getByRole("dialog");
|
||||
await expect(info.getByTestId("gutschrift-erklaerung")).toContainText("nur Gebäude");
|
||||
await expect(info.getByTestId("gutschrift-erklaerung")).toContainText("20 %");
|
||||
await expectNoHorizontalOverflow(page, "Erklärblatt Aufholhilfe");
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(info).toHaveCount(0);
|
||||
|
||||
// Gebäudeblatt: Kosten aus der Gutschrift, nichts aus dem Lager; Ausbau trotz leerem Lager möglich.
|
||||
await page.getByRole("button", { name: /^Kraftwerk 0/ }).click();
|
||||
const sheet = page.getByRole("dialog");
|
||||
await expect(sheet.getByTestId("kosten-gutschrift")).toContainText("Baugutschrift (Aufholhilfe):");
|
||||
await expect(sheet.getByTestId("kosten-gutschrift")).toContainText("aus dem Lager:");
|
||||
await expectNoHorizontalOverflow(page, "Gebäudeblatt mit Baugutschrift");
|
||||
await sheet.getByRole("button", { name: "Ausbau auf 1" }).click();
|
||||
await expect(sheet).toHaveCount(0);
|
||||
await expect(page.getByText("Kraftwerk · Ausbau auf Stufe 1")).toBeVisible();
|
||||
|
||||
const s = await readState(seed.sql, player.baseId);
|
||||
expect(s.catchUp.credit).toBeLessThan(5000);
|
||||
expect(s.resources.stahl).toBeLessThan(5);
|
||||
await expect(page.getByTestId("gutschrift-leiste")).not.toContainText("Baugutschrift 5.000");
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
// Aufholhilfe: Baugutschrift sichtbar machen – schmale Zeile unter der Ressourcenleiste, Zeile im Bauhof, Erklärblatt und
|
||||
// die Verrechnung in den Baukosten (die Gutschrift wird zuerst verbraucht, game-core splitBuildCost).
|
||||
import { useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { splitBuildCost, type Balance as CoreBalance } from "@tidefront/game-core";
|
||||
import { trpc, type BaseData } from "../lib/trpc.ts";
|
||||
import { fmtNum } from "../lib/names.ts";
|
||||
import { Icon } from "../icons.tsx";
|
||||
import { Cost, Sheet } from "../ui.tsx";
|
||||
|
||||
type CatchUp = NonNullable<BaseData["catchUp"]>;
|
||||
|
||||
const pct = (x: number) => `${fmtNum(Math.round(x * 100))} %`;
|
||||
|
||||
/** Teil der Kosten, den das Lager zahlt, und Teil aus der Baugutschrift (ohne Gutschrift: alles aus dem Lager). */
|
||||
export function useBuildCost(base: BaseData, cost: Record<string, number> | null): { stock: Record<string, number> | null; credit: Record<string, number> | null } {
|
||||
const meta = useQuery({ ...trpc.meta.queryOptions(), staleTime: Infinity });
|
||||
return buildCostSplit(base, cost, meta.data?.balance as CoreBalance | undefined);
|
||||
}
|
||||
|
||||
export function buildCostSplit(base: BaseData, cost: Record<string, number> | null, balance: CoreBalance | undefined) {
|
||||
const credit = base.catchUp?.credit ?? 0;
|
||||
if (!cost || !balance || credit <= 0) return { stock: cost, credit: null };
|
||||
const s = splitBuildCost(cost, credit, balance);
|
||||
return { stock: s.fromStock, credit: Object.keys(s.fromCredit).length ? s.fromCredit : null };
|
||||
}
|
||||
|
||||
/** Kosten im Info-Blatt: verrechnet „aus der Baugutschrift“ und „aus dem Lager“. */
|
||||
export function CreditCost({ credit, stock, have }: { credit: Record<string, number>; stock: Record<string, number>; have: Record<string, number> }) {
|
||||
return (
|
||||
<div className="text-xs space-y-1" data-testid="kosten-gutschrift">
|
||||
<div className="flex flex-wrap items-center gap-x-2"><span className="text-moos">Baugutschrift (Aufholhilfe):</span> <Cost cost={credit} /></div>
|
||||
<div className="flex flex-wrap items-center gap-x-2"><span className="text-ink2">aus dem Lager:</span> <Cost cost={stock} have={have} /></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Schmale Zeile unter der Ressourcenleiste (nur mit Gutschrift oder laufender Hilfe). */
|
||||
export function CatchUpStrip({ base }: { base: BaseData }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const c = base.catchUp;
|
||||
if (!c || (c.credit <= 0 && !(c.active && c.bonus > 0))) return null;
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={() => setOpen(true)} data-testid="gutschrift-leiste"
|
||||
className="w-full flex items-center gap-1.5 px-2 pb-1 text-[11px] text-left text-moos"
|
||||
aria-label={`Baugutschrift ${fmtNum(c.credit)} aus der Aufholhilfe – Erklärung`}>
|
||||
<Icon id="kommandozentrale" size={14} className="shrink-0" />
|
||||
<span className="mono font-semibold">Baugutschrift {fmtNum(c.credit)}</span>
|
||||
<span className="text-ink2 truncate">· Aufholhilfe{c.active && c.bonus > 0 ? ` +${pct(c.bonus)}` : ""} · nur für Gebäude</span>
|
||||
</button>
|
||||
{open && <CatchUpSheet c={c} onClose={() => setOpen(false)} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Zeile im Bauhof: Betrag, Herkunft, Erklärung. */
|
||||
export function CatchUpLine({ base }: { base: BaseData }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const c = base.catchUp;
|
||||
if (!c || (c.credit <= 0 && !(c.active && c.bonus > 0))) return null;
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={() => setOpen(true)} data-testid="gutschrift-bauhof"
|
||||
className="tap w-full mt-2 pt-2 border-t border-dotted border-rule flex items-center gap-2 text-left text-xs text-ink2">
|
||||
<Icon id="lagerkomplex" size={20} className="shrink-0" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="font-display uppercase tracking-[0.08em] text-ink mr-1">Baugutschrift</span>
|
||||
<span className="mono text-moos font-semibold">{fmtNum(c.credit)}</span> · Herkunft: Aufholhilfe
|
||||
{c.pack > 0 ? " (mit Startpaket)" : ""}{c.active && c.bonus > 0 ? ` · Zufluss +${pct(c.bonus)} der Gebäudeproduktion` : ""}.
|
||||
{" "}Wird beim Bauen zuerst verrechnet.
|
||||
</span>
|
||||
<span aria-hidden>›</span>
|
||||
</button>
|
||||
{open && <CatchUpSheet c={c} onClose={() => setOpen(false)} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Erklärblatt der Aufholhilfe. */
|
||||
export function CatchUpSheet({ c, onClose }: { c: CatchUp; onClose: () => void }) {
|
||||
const r = c.rules;
|
||||
return (
|
||||
<Sheet open onClose={onClose} title="Aufholhilfe · Baugutschrift" icon={<Icon id="lagerkomplex" size={40} />}>
|
||||
<div className="text-sm space-y-2" data-testid="gutschrift-erklaerung">
|
||||
<p>
|
||||
Bestand: <strong className="mono">{fmtNum(c.credit)}</strong> (zum Börsen-Richtwert, Stahl = 1).
|
||||
{c.ratio !== null && <> Dein Ausbau liegt bei <strong>{pct(c.ratio)}</strong> des Medians aller Häfen.</>}
|
||||
{c.active && c.bonus > 0 ? <> Zufluss jetzt: <strong>+{pct(c.bonus)}</strong> deiner Gebäudeproduktion je Stunde.</> : <> Zurzeit kein Zufluss.</>}
|
||||
</p>
|
||||
<p>
|
||||
Wer im Ausbau weit hinter dem Median liegt, bekommt stündlich eine Baugutschrift: ab unter {pct(r.from)} des Medians
|
||||
steigend, voll (+{pct(r.cap)} der Gebäudeproduktion) ab {pct(r.full)} und darunter. Ab {pct(r.from)} endet sie und beginnt erst
|
||||
unter {pct(r.resumeBelow)} wieder. Höchstbestand: {fmtNum(r.storeHours)} Stunden Zufluss.
|
||||
</p>
|
||||
<p>
|
||||
Die Gutschrift bezahlt <strong>nur Gebäude</strong> und wird beim Ausbau zuerst verrechnet (gleicher Anteil jeder Ressource),
|
||||
den Rest zahlt das Lager. Sie liegt nicht im Lager, kann nicht geplündert, gehandelt oder verschickt werden und verfällt
|
||||
zum Saisonende. Bauzeiten bleiben gleich.
|
||||
</p>
|
||||
{(c.pack > 0 || c.earned > 0) && (
|
||||
<p className="text-ink2">
|
||||
Bisher erhalten: {c.pack > 0 ? <>Startpaket {fmtNum(c.pack)}</> : null}{c.pack > 0 && c.earned > 0 ? ", " : ""}{c.earned > 0 ? <>Zufluss {fmtNum(c.earned)}</> : null}.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Handbuch-Kapitel „Aufholhilfe“: Baugutschrift für Häfen weit unter dem Median und Startpaket für Spät-Einsteiger.
|
||||
// Zahlen aus balance.catchUp (sonst die Startwerte).
|
||||
import type { ReactNode } from "react";
|
||||
import type { Balance } from "../lib/trpc.ts";
|
||||
|
||||
function P({ children }: { children: ReactNode }) {
|
||||
return <p className="text-sm text-slate-200 mb-2 leading-relaxed">{children}</p>;
|
||||
}
|
||||
|
||||
const pct = (x: number) => `${Math.round(x * 100)} %`;
|
||||
|
||||
export function CatchUpChapter({ b }: { b: Balance | undefined }) {
|
||||
const c = b?.catchUp ?? { from: 0.7, full: 0.3, cap: 0.5, resumeBelow: 0.6, minBaseAgeDays: 3, storeHours: 24, stopDay: 40, latePackFromDay: 8, latePackShare: 0.15 };
|
||||
const mid = (c.from + c.full) / 2;
|
||||
return (
|
||||
<>
|
||||
<P>Wer später einsteigt oder weit zurückliegt, bekommt eine <strong>Baugutschrift</strong>. Gemessen wird dein <strong>Ausbau</strong> (Kosten aller Gebäudestufen, wie in der Rangliste, alle Häfen zusammen) im Verhältnis zum <strong>Median</strong> aller Spieler und KI-Spieler, deren erster Hafen mindestens {c.minBaseAgeDays} Tage alt ist. Der Server rechnet das einmal je Stunde neu.</P>
|
||||
<ul className="text-sm list-disc pl-5 space-y-1 mb-2 text-slate-200">
|
||||
<li>Unter {pct(c.from)} des Medians fließt stündlich eine Gutschrift von bis zu <strong>+{pct(c.cap)} deiner Gebäudeproduktion</strong>: bei {pct(mid)} etwa +{pct(c.cap / 2)}, ab {pct(c.full)} und darunter voll +{pct(c.cap)}.</li>
|
||||
<li>Ab {pct(c.from)} endet die Hilfe; sie beginnt erst wieder, wenn du unter {pct(c.resumeBelow)} fällst. Mehr als {c.storeHours} Stunden Zufluss sammeln sich nicht an. Ab Saisontag {c.stopDay} fließt nichts mehr.</li>
|
||||
<li><strong>Startpaket:</strong> Wer seinen ersten Hafen ab Saisontag {c.latePackFromDay} gründet, bekommt einmalig {pct(c.latePackShare)} des Median-Ausbauwerts als Gutschrift.</li>
|
||||
</ul>
|
||||
<P>Die Gutschrift bezahlt <strong>nur Gebäude</strong>. Beim Ausbau wird sie zuerst verrechnet (derselbe Anteil jeder Ressource), den Rest zahlt dein Lager; im Info-Blatt eines Gebäudes siehst du beide Teile. Ein Abbruch erstattet den Gutschrift-Anteil in die Gutschrift zurück. Sie liegt nicht im Lager, lässt sich nicht plündern, handeln oder verschicken und verfällt zum Saisonende. Bauzeiten bleiben unverändert.</P>
|
||||
<P>Die Hilfe gilt für Menschen und KI-Spieler gleich. Sie endet weit unter dem Median – an der Spitze zieht damit niemand vorbei. Absichtlich klein bleiben lohnt nicht: Wer nur rüstet, kann die Gutschrift nicht ausgeben; wer baut, holt auf und beendet sie damit selbst. Bestand und Herkunft zeigen die Zeile unter der Ressourcenleiste und der Bauhof.</P>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { Icon } from "../icons.tsx";
|
||||
import { ResourceSheet } from "./ResourceSheet.tsx";
|
||||
import { HarborSwitcher } from "./HarborSwitcher.tsx";
|
||||
import { MenuSheet, type MenuItem } from "./MenuSheet.tsx";
|
||||
import { CatchUpStrip } from "./CatchUp.tsx";
|
||||
export type { MenuItem } from "./MenuSheet.tsx";
|
||||
|
||||
function short(n: number): string {
|
||||
@@ -91,6 +92,7 @@ export function ResourceBar({ base, asOf, now, onMenu, onSwitchBase, onPlanFound
|
||||
<span className="text-[11px] leading-none font-display tracking-[0.04em]">Menü</span>
|
||||
</button>
|
||||
</div>
|
||||
<CatchUpStrip base={base} />{/* Aufholhilfe: Baugutschrift */}
|
||||
{open && <ResourceSheet base={base} res={open} amount={liveAmount(base, asOf, now, open)} onClose={() => setOpen(null)} />}
|
||||
<MenuSheet open={menu} onClose={() => setMenu(false)} onPick={(i) => { setMenu(false); onMenu(i); }} />
|
||||
</header>
|
||||
|
||||
@@ -142,6 +142,12 @@ export function AdminStats() {
|
||||
<StatTable rows={[["Ø Stufe Kommandozentrale", fmtNum(s.economy.avgKommandozentrale, 1)]]} />
|
||||
<Sub>Gebäudestufen (Anzahl Häfen je Stufe)</Sub>
|
||||
<LevelGrid rows={s.economy.buildings.map((b) => ({ ...b, label: label(b.id) }))} />
|
||||
{(s.economy.catchUp ?? []).length > 0 && (
|
||||
<>
|
||||
<Sub>Aufholhilfe (Baugutschrift: Bestand · Summe Zufluss und Startpaket)</Sub>
|
||||
<StatTable rows={s.economy.catchUp.map((c) => [`${c.name}${c.active ? ` · aktiv +${fmtNum(c.bonus * 100)} %` : ""}`, `${fmtNum(c.credit)} · ${fmtNum(c.total)}`])} />
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{s.marketNews && (
|
||||
|
||||
@@ -25,6 +25,8 @@ import { Breakdown } from "../components/Breakdown.tsx";
|
||||
import { IntelPanel, SabotageBanner, sabotagedUntil } from "../components/Intel.tsx"; // Nachrichtendienst
|
||||
import { BlockadeBanner } from "../components/Naval.tsx"; // See: Blockade („blockiert bis …“)
|
||||
import { buildingLive, harborWeather } from "../lib/live-art.ts"; // Bewegte Gebäude
|
||||
import { CatchUpLine, CreditCost, buildCostSplit, useBuildCost } from "../components/CatchUp.tsx"; // Aufholhilfe: Baugutschrift
|
||||
import type { Balance as CoreBalance } from "@tidefront/game-core";
|
||||
|
||||
const invalidateBase = () => [trpc.base.pathFilter().queryKey];
|
||||
|
||||
@@ -105,7 +107,7 @@ export function BaseScreen(props: {
|
||||
{GROUPS.map((g) => (
|
||||
<Card key={g.title} title={g.title}>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{g.ids.map((id) => byId[id] && <BuildingTile key={id} b={byId[id]} live={live(byId[id])} sabotaged={sabotagedUntil(base, id, now) !== null} res={res} queueFull={queueFull} running={queue[0]?.buildingId === id} queued={queue.some((o) => o.buildingId === id)} onOpen={() => setSheet(id)} />)}
|
||||
{g.ids.map((id) => byId[id] && <BuildingTile key={id} b={byId[id]} stock={buildCostSplit(base, byId[id].cost, meta.data?.balance as CoreBalance | undefined).stock} live={live(byId[id])} sabotaged={sabotagedUntil(base, id, now) !== null} res={res} queueFull={queueFull} running={queue[0]?.buildingId === id} queued={queue.some((o) => o.buildingId === id)} onOpen={() => setSheet(id)} />)}
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
@@ -195,6 +197,7 @@ function BuildYard({ base, now, onResearch }: { base: BaseData; now: number; onR
|
||||
<ErrorLine text={cancel.error} code={cancel.code} />
|
||||
<p className="text-xs text-ink2 flex items-center gap-1.5 mt-2"><span className="diamond bg-moos shrink-0" aria-hidden="true" /> = jetzt ausbaubar (Rohstoffe reichen, Platz in der Schlange frei)</p>
|
||||
<ResearchLine base={base} now={now} onOpen={onResearch} />
|
||||
<CatchUpLine base={base} />
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -216,8 +219,8 @@ function ResearchLine({ base, now, onOpen }: { base: BaseData; now: number; onOp
|
||||
);
|
||||
}
|
||||
|
||||
function BuildingTile({ b, live, res, queueFull, running, queued, onOpen, sabotaged }: { b: Building; live: Live; res: Record<string, number>; queueFull: boolean; running: boolean; queued: boolean; onOpen: () => void; sabotaged?: boolean }) {
|
||||
const can = !queueFull && !b.requires && b.planned < b.maxAllowed && affordable(b.cost, res);
|
||||
function BuildingTile({ b, stock, live, res, queueFull, running, queued, onOpen, sabotaged }: { b: Building; stock: Record<string, number> | null; live: Live; res: Record<string, number>; queueFull: boolean; running: boolean; queued: boolean; onOpen: () => void; sabotaged?: boolean }) {
|
||||
const can = !queueFull && !b.requires && b.planned < b.maxAllowed && affordable(stock, res); // Aufholhilfe: nach Abzug der Baugutschrift
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
@@ -241,7 +244,8 @@ function BuildingSheet({ b, live, base, res, onClose, onTroops, onResearch }: {
|
||||
const balance = meta.data?.balance;
|
||||
const capped = b.planned >= b.maxAllowed;
|
||||
const maxed = !b.cost;
|
||||
const enough = affordable(b.cost, res);
|
||||
const split = useBuildCost(base, b.cost); // Aufholhilfe: Baugutschrift zuerst verrechnet
|
||||
const enough = affordable(split.stock, res);
|
||||
const used = base.buildQueue.length;
|
||||
const queueFull = used >= base.buildQueueSlots;
|
||||
const target = b.planned + 1;
|
||||
@@ -290,7 +294,7 @@ function BuildingSheet({ b, live, base, res, onClose, onTroops, onResearch }: {
|
||||
{!maxed && (
|
||||
<div className="rounded-xl bg-paper border border-rule p-2 mb-3">
|
||||
<div className="text-[11px] uppercase tracking-wider text-slate-400 mb-1">Kosten</div>
|
||||
<Cost cost={b.cost} have={res} />
|
||||
{split.credit && split.stock ? <CreditCost credit={split.credit} stock={split.stock} have={res} /> : <Cost cost={b.cost} have={res} />}
|
||||
{b.seconds !== null && <div className="text-sm mt-1 flex items-center gap-1"><Icon id="uhr" size={16} /> {fmtSeconds(b.seconds)}{buildNote && <span className="text-xs text-emerald-300">({buildNote})</span>}</div>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -19,6 +19,7 @@ import { FieldsChapter } from "../components/FieldsChapter.tsx"; // Felder
|
||||
import { HarborsChapter } from "../components/HarborsChapter.tsx"; // Mehrere Häfen
|
||||
import { BotsChapter } from "../components/BotsChapter.tsx"; // KI-Spieler
|
||||
import { LagebildChapter } from "../components/LagebildChapter.tsx"; // Lagebild
|
||||
import { CatchUpChapter } from "../components/CatchUpChapter.tsx"; // Aufholhilfe
|
||||
import { requestBugReport } from "../lib/bug-log.ts";
|
||||
import { HScroll } from "../components/HScroll.tsx";
|
||||
|
||||
@@ -238,6 +239,7 @@ export function Handbook({ onClose, onLogout, playerName, initialView, onView }:
|
||||
},
|
||||
// Erfolge (Abzeichen) und Wochenziele (components/AchievementsChapter.tsx)
|
||||
{ id: "erfolge", icon: "hafenmeister", title: "Erfolge und Wochenziele", body: <AchievementsChapter b={b} /> },
|
||||
{ id: "aufholhilfe", icon: "lagerkomplex", title: "Aufholhilfe", body: <CatchUpChapter b={b} /> }, // Baugutschrift
|
||||
{
|
||||
id: "saison", icon: "nav-bericht", title: "Saison und Wertung",
|
||||
body: (
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
runMarketNews,
|
||||
runMorningSummaries,
|
||||
runBotsDue,
|
||||
runCatchUp,
|
||||
runEventWatchdog,
|
||||
rankSnapshot,
|
||||
type Engine,
|
||||
@@ -95,6 +96,11 @@ async function maintenance(): Promise<void> {
|
||||
await step("nudge cleanup", () => cleanupNudges(db));
|
||||
// PvP: Rang-Momentaufnahme des Spieltags (Kopfgeld, Mutfaktor) bald nach Mitternacht festhalten.
|
||||
await step("pvp rank snapshot", () => rankSnapshot(db, Date.now()));
|
||||
// Aufholhilfe: einmal je Stunde Median der Ausbaupunkte, Rückstand und Zufluss der Baugutschrift.
|
||||
await step("catch up", async () => {
|
||||
const n = await runCatchUp(engine, Date.now());
|
||||
if (n > 0) log("catch up", { bases: n });
|
||||
});
|
||||
}
|
||||
|
||||
async function loop() {
|
||||
|
||||
@@ -412,6 +412,35 @@ Werte unter `market.news` (seit v1.5), Kern `packages/game-core/src/market/news.
|
||||
Nester sind wieder besetzt, die Börse steht auf Richtwert, Tagesbefehle und Serien verfallen. Konten, Nachrichten und die Ruhmeshalle bleiben.
|
||||
Jeder Spieler wählt einen neuen Hafen und erhält erneut Anfängerschutz.
|
||||
|
||||
## Aufholhilfe
|
||||
|
||||
Baugutschrift für Häfen weit unter dem Median und für Spät-Einsteiger (Balance-Block `catchUp`;
|
||||
Vorlage „Aufholhilfe“ (docs/VORLAGE-AUFHOLHILFE.md) mit Nutzerentscheiden vom 27.11.2026; Rechnung
|
||||
`node packages/game-core/sim/aufholhilfe.ts`). Gilt für Menschen und KI-Spieler gleich.
|
||||
|
||||
- **Rückstand r** = eigene Ausbaupunkte (Kostenwert aller gebauten Gebäudestufen, alle Häfen) / Median der
|
||||
Ausbaupunkte aller Spieler (KI eingeschlossen), deren erster Hafen mindestens `minBaseAgeDays` (3) Tage alt ist.
|
||||
Der Worker rechnet einmal je `refreshMinutes` (60) und speichert den Median zwischen (`server_setting catch_up`).
|
||||
- **Bonus b** = `cap` × clamp((`from` − r) / (`from` − `full`); 0; 1) mit `from` 0,70, `full` 0,30, `cap` 0,50:
|
||||
|
||||
| r | ≥ 70 % | 60 % | 50 % | 40 % | ≤ 30 % |
|
||||
|---|---|---|---|---|---|
|
||||
| b | 0 | +12,5 % | +25 % | +37,5 % | +50 % |
|
||||
|
||||
- **Hysterese:** Die Hilfe endet bei r ≥ 70 % und beginnt erst wieder unter `resumeBelow` (60 %).
|
||||
- **Zufluss:** je Stunde b × Gebäudeproduktion des Hafens (ohne Grundrate, nach Strom, ohne Forschungszuschläge) zum
|
||||
Richtwert in das Konto `catchUp` des Hafens; höchstens `maxCatchUpHours` (2) Stunden je Lauf, Bestand höchstens
|
||||
`storeHours` (24) Stunden Zufluss (darüber ruht er). Ab Saisontag `stopDay` (40) kein Zufluss mehr.
|
||||
- **Startpaket:** Wer seinen ersten Hafen der Saison ab Saisontag `latePackFromDay` (8; Tag 1 = Saisonbeginn) wählt,
|
||||
erhält einmalig `latePackShare` (15 %) des Median-Ausbauwerts als Gutschrift (bei der Hafenwahl, Median aus dem
|
||||
Zwischenspeicher). Kolonien erhalten kein Paket.
|
||||
- **Verwendung:** Die Gutschrift bezahlt nur Gebäudestufen und wird beim Ausbau **zuerst** verbraucht: Sie deckt
|
||||
denselben Anteil jeder Ressource der Kosten (abgerundet), den Rest zahlt das Lager. Der Auftrag merkt sich den
|
||||
Gutschrift-Teil; ein Abbruch erstattet ihn (anteilig wie üblich) in die Gutschrift, nicht ins Lager.
|
||||
- Die Gutschrift zählt nicht zum Lager, ist nicht plünderbar, handelbar oder transportierbar und verfällt mit den
|
||||
Häfen zum Saisonende. Bauzeiten ändern sich nicht. Einheiten, Anlagen, Forschung kann sie nicht bezahlen.
|
||||
- Die Verwaltung (Statistik → Wirtschaft) zeigt je Spieler „aktiv“, Bonus, Bestand und Summe aus Zufluss und Paket.
|
||||
|
||||
## Tagesbefehle
|
||||
|
||||
- Spieltag: Tageswechsel um 0:00 Uhr in der Zeitzone des Servers (`TZ`, Vorgabe `Europe/Berlin`).
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "v1.26",
|
||||
"version": "v1.27",
|
||||
"resources": ["stahl", "treibstoff", "elektronik", "proviant"],
|
||||
"start": { "stahl": 2000, "treibstoff": 1000, "elektronik": 500, "proviant": 1000 },
|
||||
"baseTricklePerHour": { "stahl": 20, "treibstoff": 10, "elektronik": 5, "proviant": 15 },
|
||||
@@ -488,5 +488,10 @@
|
||||
"expandFromCommandLevel": 5, "fields": "all", "trade": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"catchUp": {
|
||||
"from": 0.7, "full": 0.3, "cap": 0.5, "resumeBelow": 0.6, "minBaseAgeDays": 3,
|
||||
"storeHours": 24, "stopDay": 40, "latePackFromDay": 8, "latePackShare": 0.15,
|
||||
"refreshMinutes": 60, "maxCatchUpHours": 2
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,8 @@ export interface AdminStats {
|
||||
avgKommandozentrale: number;
|
||||
/** levels[i] = Anzahl Stützpunkte mit Stufe i. */
|
||||
buildings: { id: string; avg: number; max: number; levels: number[] }[];
|
||||
/** Aufholhilfe: Spieler mit Konto (aktiv, Bonus, Bestand, Summe aus Zufluss und Startpaket), alle Häfen summiert. */
|
||||
catchUp: { playerId: number; name: string; active: boolean; bonus: number; credit: number; total: number }[];
|
||||
};
|
||||
anomalies: {
|
||||
richPlayers: { playerId: number; name: string; total: number; ratio: number }[];
|
||||
@@ -255,6 +257,13 @@ export async function adminStats(db: Db, days: StatsDays, nowMs = Date.now(), tz
|
||||
for (const id of buildingIds) levels.get(id)!.push(s.buildings[id] ?? 0);
|
||||
}
|
||||
const totals = [...byPlayer.values()];
|
||||
const catchUp = new Map<number, AdminStats["economy"]["catchUp"][number]>();
|
||||
for (const b of bases) {
|
||||
const c = b.state.catchUp;
|
||||
if (!c) continue;
|
||||
const e = catchUp.get(b.player_id) ?? { playerId: b.player_id, name: b.name, active: false, bonus: 0, credit: 0, total: 0 };
|
||||
catchUp.set(b.player_id, { ...e, active: e.active || c.active, bonus: Math.max(e.bonus, c.bonus), credit: e.credit + Math.floor(c.credit), total: e.total + Math.floor(c.earned + (c.pack ?? 0)) });
|
||||
}
|
||||
const buildings = buildingIds.map((id) => {
|
||||
const ls = levels.get(id)!;
|
||||
const max = ls.reduce((a, b) => Math.max(a, b), 0);
|
||||
@@ -302,7 +311,7 @@ export async function adminStats(db: Db, days: StatsDays, nowMs = Date.now(), tz
|
||||
},
|
||||
combat,
|
||||
nests: nestRows.map((r) => ({ playerId: r.id, name: r.name, maxLevel: r.maxl, wins: r.wins, attempts: r.attempts })),
|
||||
economy: { bases: bases.length, colonies: bases.filter((b) => !b.is_home).length, avgKommandozentrale: kz?.avg ?? 0, buildings },
|
||||
economy: { bases: bases.length, colonies: bases.filter((b) => !b.is_home).length, avgKommandozentrale: kz?.avg ?? 0, buildings, catchUp: [...catchUp.values()].sort((a, b) => b.total - a.total) },
|
||||
anomalies: {
|
||||
richPlayers,
|
||||
repeatedAttacks: rep.map((r) => ({ attacker: r.attacker, defender: r.defender, maxPerDay: r.maxday, total: r.total })),
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// geprüft wird mit denselben Kernfunktionen wie in den Befehlen (startUpgrade, startTraining, startResearch),
|
||||
// ausgeführt wird danach über die Befehle (bots-run.ts). Ideen aus game-core/sim/bot.ts (Bauordnung, Doktrin).
|
||||
import {
|
||||
buildCredit,
|
||||
commandPoints,
|
||||
fleetTotals,
|
||||
maxAllowedLevel,
|
||||
@@ -10,6 +11,7 @@ import {
|
||||
productionRates,
|
||||
researchCost,
|
||||
satelliteOf,
|
||||
splitBuildCost,
|
||||
startResearch,
|
||||
startTraining,
|
||||
startUpgrade,
|
||||
@@ -215,7 +217,8 @@ function tryBuild(c: PlanCtx, candidates: string[], n: number, save: boolean): {
|
||||
const r = startUpgrade(c.state, id, c.nowMs, balance, c.mods);
|
||||
if (r.ok) return { id };
|
||||
if (r.code === "insufficient_resources" && save) {
|
||||
const cost = upgradeCost(id, plannedLevel(c.state, id), balance);
|
||||
// Aufholhilfe: zurückgelegt wird nur, was die Baugutschrift nicht deckt (startUpgrade verbraucht sie zuerst).
|
||||
const cost = splitBuildCost(upgradeCost(id, plannedLevel(c.state, id), balance), buildCredit(c.state), balance).fromStock;
|
||||
// Passt der Ausbau gar nicht ins Lager, hilft Sparen nicht: nächster Kandidat (meist das Lager selbst).
|
||||
if (Object.values(cost).some((n) => n > storageCapacity(c.state, balance, c.mods))) continue;
|
||||
c.reserve = addRes(c.reserve ?? {}, cost);
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
// Aufholhilfe (game-core catch-up.ts, docs/REGELN.md „Aufholhilfe“): einmal je Stunde im Worker Median der Ausbaupunkte,
|
||||
// Rückstand je Spieler und Zufluss der Baugutschrift; Startpaket für Spät-Einsteiger bei der Hafenwahl. Leichtgewichtig
|
||||
// für den Raspberry Pi: eine Abfrage nur der Gebäudestufen aller Häfen, geschrieben werden nur Häfen mit Hilfe oder
|
||||
// Konto (je Hafen eine kurze Transaktion mit Zeilensperre, damit kein gleichzeitiger Bauauftrag Gutschrift verliert).
|
||||
import { sql } from "drizzle-orm";
|
||||
import {
|
||||
accrueCatchUp,
|
||||
catchUpBonus,
|
||||
catchUpOf,
|
||||
emptyCatchUp,
|
||||
median,
|
||||
productionRates,
|
||||
refValue,
|
||||
type BaseState,
|
||||
type CatchUpBalance,
|
||||
type CatchUpState,
|
||||
type Counts,
|
||||
} from "@tidefront/game-core";
|
||||
import type { DbOrTx } from "@tidefront/db";
|
||||
import { balance, type Engine } from "./context.ts";
|
||||
import { buildingValue } from "./scoring.ts"; // Ausbaupunkte nur lesen (Kostenwert aller Gebäudestufen)
|
||||
import { runningSeason } from "./season.ts";
|
||||
import { getSetting, setSetting } from "./settings.ts";
|
||||
|
||||
const DAY_MS = 86400000;
|
||||
/** Zwischenspeicher des letzten Laufs (server_setting): Zeitpunkt und Median-Ausbauwert. */
|
||||
export const CATCH_UP_KEY = "catch_up";
|
||||
|
||||
export interface CatchUpSnapshot {
|
||||
atMs: number;
|
||||
/** Median der Ausbauwerte (Richtwert) der Spieler, deren erster Hafen mindestens minBaseAgeDays alt ist; null: keiner. */
|
||||
median: number | null;
|
||||
/** Ausbauwert je Spieler (alle Häfen). */
|
||||
values: Map<number, number>;
|
||||
/** Saisontag (1 = erster Tag); null ohne laufende Saison. */
|
||||
seasonDay: number | null;
|
||||
}
|
||||
|
||||
/** Saisontag zum Zeitpunkt nowMs (1 = erster Tag der Saison). */
|
||||
export function seasonDayAt(seasonStartMs: number, nowMs: number): number {
|
||||
return Math.floor((nowMs - seasonStartMs) / DAY_MS) + 1;
|
||||
}
|
||||
|
||||
/** Median der Ausbaupunkte (Menschen und KI) und Ausbauwert je Spieler – eine Abfrage, nur Gebäudestufen. */
|
||||
export async function catchUpSnapshot(db: DbOrTx, nowMs: number, cu: CatchUpBalance): Promise<CatchUpSnapshot> {
|
||||
const rows = await db.execute<{ player_id: number; first_ms: number; buildings: Counts | null }>(sql`
|
||||
select player_id, (extract(epoch from min(created_at) over (partition by player_id)) * 1000)::float8 as first_ms,
|
||||
state->'buildings' as buildings
|
||||
from base`);
|
||||
const values = new Map<number, number>();
|
||||
const first = new Map<number, number>();
|
||||
for (const r of rows) {
|
||||
values.set(r.player_id, (values.get(r.player_id) ?? 0) + buildingValue(r.buildings ?? {}));
|
||||
first.set(r.player_id, r.first_ms);
|
||||
}
|
||||
const oldEnough = [...values.entries()].filter(([id]) => nowMs - (first.get(id) ?? nowMs) >= cu.minBaseAgeDays * DAY_MS);
|
||||
const m = median(oldEnough.map(([, v]) => v));
|
||||
const season = await runningSeason(db);
|
||||
return { atMs: nowMs, median: m !== null && m > 0 ? m : null, values, seasonDay: season ? seasonDayAt(season.startsAt.getTime(), nowMs) : null };
|
||||
}
|
||||
|
||||
/** Zuletzt zwischengespeicherter Median (höchstens zwei Laufabstände alt), sonst null. */
|
||||
async function cachedMedian(db: DbOrTx, nowMs: number, cu: CatchUpBalance): Promise<number | null | undefined> {
|
||||
const raw = await getSetting(db, CATCH_UP_KEY);
|
||||
if (!raw) return undefined;
|
||||
try {
|
||||
const c = JSON.parse(raw) as { atMs: number; median: number | null };
|
||||
return nowMs - c.atMs <= 2 * cu.refreshMinutes * 60000 ? c.median : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stündlicher Lauf (Worker, alle 10 Minuten aufgerufen; rechnet nur, wenn refreshMinutes seit dem letzten Lauf vergangen
|
||||
* sind, oder mit force). Liefert die Zahl der geschriebenen Häfen.
|
||||
*/
|
||||
export async function runCatchUp(engine: Engine, nowMs: number, opts: { force?: boolean } = {}): Promise<number> {
|
||||
const cu = catchUpOf(balance);
|
||||
if (!cu) return 0;
|
||||
if (!opts.force) {
|
||||
const raw = await getSetting(engine.db, CATCH_UP_KEY);
|
||||
const last = raw ? (JSON.parse(raw) as { atMs?: number }).atMs ?? 0 : 0;
|
||||
if (nowMs - last < cu.refreshMinutes * 60000) return 0;
|
||||
}
|
||||
const snap = await catchUpSnapshot(engine.db, nowMs, cu);
|
||||
await setSetting(engine.db, CATCH_UP_KEY, JSON.stringify({ atMs: nowMs, median: snap.median }));
|
||||
// Ab stopDay kein Zufluss mehr (Bonus und Verhältnis werden weiter angezeigt).
|
||||
const flowing = snap.seasonDay !== null && snap.seasonDay < cu.stopDay;
|
||||
const bases = await engine.db.execute<{ id: number; player_id: number; has: boolean }>(sql`
|
||||
select id, player_id, state ? 'catchUp' as has from base order by id`);
|
||||
let written = 0;
|
||||
for (const b of bases) {
|
||||
const value = snap.values.get(b.player_id) ?? 0;
|
||||
const ratio = snap.median === null ? null : value / snap.median;
|
||||
// Häfen ohne Konto und ohne Aussicht auf Hilfe bleiben unberührt (keine Schreiblast).
|
||||
if (!b.has && (ratio === null || ratio >= cu.from)) continue;
|
||||
const done = await engine.db.transaction(async (tx) => {
|
||||
const [row] = await tx.execute<{ state: BaseState }>(sql`select state from base where id = ${b.id} for update`);
|
||||
if (!row) return false;
|
||||
const prev = row.state.catchUp ?? null;
|
||||
const { bonus, active } = catchUpBonus(ratio, cu, prev);
|
||||
if (!prev && bonus <= 0) return false;
|
||||
const base: CatchUpState = { ...(prev ?? emptyCatchUp(nowMs)), bonus, active, ratio };
|
||||
const perHour = refValue(productionRates(row.state, balance, undefined, nowMs).buildingPerHour, balance);
|
||||
// Zufluss mit dem Bonus des vorigen Laufs (er galt die vergangene Stunde), danach der neue Bonus.
|
||||
const next = prev ? { ...accrueCatchUp(prev, perHour, nowMs, cu, flowing), bonus, active, ratio } : base;
|
||||
await tx.execute(sql`update base set state = jsonb_set(state, '{catchUp}', ${JSON.stringify(next)}::jsonb) where id = ${b.id}`);
|
||||
return true;
|
||||
});
|
||||
if (done) written++;
|
||||
}
|
||||
return written;
|
||||
}
|
||||
|
||||
/**
|
||||
* Startpaket für Spät-Einsteiger (Hafenwahl, erster Hafen der Saison): ab Saisontag latePackFromDay latePackShare des
|
||||
* Median-Ausbauwerts als Baugutschrift. Median aus dem Zwischenspeicher des Workers, sonst frisch gerechnet.
|
||||
*/
|
||||
export async function latePackState(db: DbOrTx, nowMs: number): Promise<CatchUpState | null> {
|
||||
const cu = catchUpOf(balance);
|
||||
if (!cu || cu.latePackShare <= 0) return null;
|
||||
const season = await runningSeason(db);
|
||||
if (!season || seasonDayAt(season.startsAt.getTime(), nowMs) < cu.latePackFromDay) return null;
|
||||
let m = await cachedMedian(db, nowMs, cu);
|
||||
if (m === undefined) m = (await catchUpSnapshot(db, nowMs, cu)).median;
|
||||
if (!m) return null;
|
||||
const pack = Math.round(cu.latePackShare * m);
|
||||
return pack > 0 ? { ...emptyCatchUp(nowMs), credit: pack, pack } : null;
|
||||
}
|
||||
|
||||
/** Anzeige im Hafen: Bestand, Bonus, Verhältnis, Herkunft (Startpaket, Zufluss). Null ohne Konto. */
|
||||
export function catchUpView(s: BaseState) {
|
||||
const c = s.catchUp;
|
||||
const cu = catchUpOf(balance);
|
||||
if (!c || !cu) return null;
|
||||
return {
|
||||
credit: Math.floor(c.credit),
|
||||
bonus: c.bonus,
|
||||
ratio: c.ratio,
|
||||
active: c.active,
|
||||
earned: Math.floor(c.earned),
|
||||
pack: c.pack ?? 0,
|
||||
/** Regelwerte für die Erklärung. */
|
||||
rules: { from: cu.from, full: cu.full, cap: cu.cap, resumeBelow: cu.resumeBelow, storeHours: cu.storeHours },
|
||||
};
|
||||
}
|
||||
@@ -51,6 +51,7 @@ import { createConvoy, isNavalInput, launchNaval, tradeBlocked, transportConvoyR
|
||||
import { launchField } from "./fields-missions.ts"; // Felder
|
||||
import { FOUNDING_TYPE, TRANSFER_TYPE, launchExpansion } from "./expansion.ts"; // Mehrere Häfen
|
||||
import { endBeginnerElsewhere } from "./pvp.ts"; // PvP: Anfängerschutz endet beim ersten Spielerüberfall
|
||||
import { latePackState } from "./catch-up.ts"; // Aufholhilfe: Startpaket für Spät-Einsteiger
|
||||
|
||||
export type Rejected = { ok: false; code: string };
|
||||
type Draft<T> = T | (Rejected & { keepWrites?: boolean });
|
||||
@@ -144,6 +145,9 @@ export function chooseBase(engine: Engine, playerId: number, key: string, input:
|
||||
const state: BaseState = createBase(balance, ctx.nowMs, hexCenter(input.col, input.row));
|
||||
// IANA-Zeitzone (Sommerzeit); ungültig oder fehlend: fester Versatz wie bisher.
|
||||
state.protection = createProtection(ctx.nowMs, input.nightShieldStartHour, input.tzOffsetMinutes, input.timeZone ?? null);
|
||||
// Aufholhilfe: erster Hafen ab Saisontag 8 (Menschen und KI) bekommt das Startpaket als Baugutschrift.
|
||||
const pack = await latePackState(ctx.tx, ctx.nowMs);
|
||||
if (pack) state.catchUp = pack;
|
||||
const inserted = await ctx.tx
|
||||
.insert(tables.base)
|
||||
.values({ playerId, name: input.name, col: input.col, row: input.row, state, isHome: true }) // erster Hafen = Heimathafen
|
||||
|
||||
@@ -116,3 +116,4 @@ export { bumpMapGeneration, enableMapCache } from "./map-cache.ts"; // world.map
|
||||
export { rankSnapshot, clearRankSnapshot, colluded, bountyByPlayer, type RankSnapshot } from "./pvp.ts"; // Spieler gegen Spieler
|
||||
export { recordTies } from "./pvp-ties.ts";
|
||||
export { pvpTargetView, suspiciousPairs, setReportExcluded } from "./pvp-view.ts";
|
||||
export * from "./catch-up.ts"; // Aufholhilfe: Baugutschrift (stündlicher Lauf, Startpaket)
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
type Mission,
|
||||
type ResourceMap,
|
||||
} from "@tidefront/game-core";
|
||||
import { catchUpView } from "./catch-up.ts"; // Aufholhilfe
|
||||
import { hexCenter, hexDistanceKm, nearestTradePortBySea } from "@tidefront/world";
|
||||
import { tables, type DbOrTx } from "@tidefront/db";
|
||||
import { balance, marketBalance, GameError, type Engine } from "./context.ts";
|
||||
@@ -199,6 +200,8 @@ export async function baseView(engine: Engine, playerId: number, baseId?: number
|
||||
buildings,
|
||||
buildQueue: s.buildQueue,
|
||||
buildQueueSlots: balance.building.queueSlots,
|
||||
/** Aufholhilfe: Baugutschrift (Bestand, Bonus, Herkunft); null ohne Konto. */
|
||||
catchUp: catchUpView(s),
|
||||
trainingQueue: s.trainingQueue,
|
||||
units,
|
||||
defenses: Object.keys(balance.defenses).map((id) => ({ id, count: s.defenses[id] ?? 0 })),
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
// Aufholhilfe (Server): Startpaket ab Saisontag 8 einmalig, stündlicher Zufluss nach Rückstand der Ausbaupunkte, Gutschrift
|
||||
// bezahlt nur Gebäude (Bots wie Menschen über startUpgrade), ist weder handel- noch plünderbar.
|
||||
import { after, before, test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { createDb, migrateDb, tables } from "@tidefront/db";
|
||||
import { COLS, ROWS, isCoast, isTradePortHex } from "@tidefront/world";
|
||||
import { applyDefenseResult, defenderFromBase, refValue, upgradeCost, type Balance, type BaseState, type BattleReport } from "@tidefront/game-core";
|
||||
import {
|
||||
balance,
|
||||
baseView,
|
||||
buildingValue,
|
||||
cancelBuild,
|
||||
chooseBase,
|
||||
createOffer,
|
||||
register,
|
||||
runCatchUp,
|
||||
seed,
|
||||
train,
|
||||
upgrade,
|
||||
type Engine,
|
||||
} from "../src/index.ts";
|
||||
|
||||
const url = process.env.TEST_DATABASE_URL;
|
||||
const { db, client } = createDb(url ?? "postgres://invalid", 10);
|
||||
const engine: Engine = { db, notify: () => {}, log: () => {} };
|
||||
const bal = balance as unknown as Balance;
|
||||
const cu = bal.catchUp!;
|
||||
const DAY = 86400000;
|
||||
let keyN = 0;
|
||||
const key = () => `cu${++keyN}-${Date.now()}`;
|
||||
|
||||
before(async () => {
|
||||
if (!url) throw new Error("TEST_DATABASE_URL fehlt");
|
||||
await db.execute(sql`drop schema if exists public cascade; drop schema if exists drizzle cascade; create schema public;`);
|
||||
await migrateDb(db);
|
||||
await seed(db, "TEST:100");
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await client.end();
|
||||
});
|
||||
|
||||
/** Freie Küstenfelder (kein Hafen, Nest, Feld, Handelshafen), weit auseinander. */
|
||||
async function freeHex(n: number) {
|
||||
const taken = new Set([
|
||||
...(await db.select({ col: tables.base.col, row: tables.base.row }).from(tables.base)),
|
||||
...(await db.select({ col: tables.nest.col, row: tables.nest.row }).from(tables.nest)),
|
||||
...(await db.select({ col: tables.resourceField.col, row: tables.resourceField.row }).from(tables.resourceField)),
|
||||
].map((x) => `${x.col},${x.row}`));
|
||||
let i = 0;
|
||||
for (let row = 5; row < ROWS; row += 7) for (let col = 3; col < COLS; col += 5) {
|
||||
if (!isCoast(col, row) || isTradePortHex(col, row) || taken.has(`${col},${row}`)) continue;
|
||||
if (i++ === n) return { col, row };
|
||||
}
|
||||
throw new Error("kein freies Feld");
|
||||
}
|
||||
|
||||
async function newPlayer(name: string) {
|
||||
const p = await register(db, { inviteCode: "TEST", name, password: "geheim123" });
|
||||
const r = await chooseBase(engine, p.playerId, key(), { ...(await freeHex(0)), name: `Hafen ${name}`, nightShieldStartHour: null, tzOffsetMinutes: 0 });
|
||||
assert.equal(r.ok, true, JSON.stringify(r));
|
||||
return { playerId: p.playerId, baseId: (r as { baseId: number }).baseId };
|
||||
}
|
||||
|
||||
async function stateOf(baseId: number): Promise<BaseState> {
|
||||
const [b] = await db.select({ state: tables.base.state }).from(tables.base).where(eq(tables.base.id, baseId));
|
||||
return b.state as BaseState;
|
||||
}
|
||||
|
||||
async function patch(baseId: number, fn: (s: BaseState) => BaseState) {
|
||||
await db.update(tables.base).set({ state: fn(await stateOf(baseId)) }).where(eq(tables.base.id, baseId));
|
||||
}
|
||||
|
||||
async function setSeasonStart(daysAgo: number) {
|
||||
await db.update(tables.season).set({ startsAt: new Date(Date.now() - daysAgo * DAY) }).where(eq(tables.season.status, "running"));
|
||||
}
|
||||
|
||||
const BIG = { stahlwerk: 12, raffinerie: 10, chipfabrik: 8, versorgungshof: 8, kraftwerk: 10, lagerkomplex: 8, kommandozentrale: 8, kaserne: 4, hafenkommandantur: 4 };
|
||||
const ZERO = { stahl: 0, treibstoff: 0, elektronik: 0, proviant: 0 };
|
||||
|
||||
let veteran: { playerId: number; baseId: number };
|
||||
let late: { playerId: number; baseId: number };
|
||||
|
||||
test("Frühe Saison: kein Startpaket; ab Saisontag 8: 15 % des Median-Ausbauwerts, einmalig", async () => {
|
||||
await setSeasonStart(1);
|
||||
veteran = await newPlayer("Alteingesessen");
|
||||
assert.equal((await stateOf(veteran.baseId)).catchUp, undefined, "Tag 2: kein Paket");
|
||||
// Der Alteingesessene ist seit 9 Tagen dabei und hat ausgebaut (Median-Grundlage: Hafen ≥ 3 Tage alt).
|
||||
await patch(veteran.baseId, (s) => ({ ...s, buildings: { ...s.buildings, ...BIG } }));
|
||||
await db.update(tables.base).set({ createdAt: new Date(Date.now() - 9 * DAY) }).where(eq(tables.base.id, veteran.baseId));
|
||||
await setSeasonStart(9); // Saisontag 10
|
||||
late = await newPlayer("Spaetling");
|
||||
const s = await stateOf(late.baseId);
|
||||
const median = buildingValue(BIG);
|
||||
assert.ok(s.catchUp, "Startpaket fehlt");
|
||||
assert.equal(s.catchUp.pack, Math.round(cu.latePackShare * median));
|
||||
assert.equal(s.catchUp.credit, s.catchUp.pack);
|
||||
// Einmalig: eine zweite Hafenwahl ist nicht möglich, die Gutschrift bleibt.
|
||||
const again = await chooseBase(engine, late.playerId, key(), { ...(await freeHex(0)), name: "Zweiter", nightShieldStartHour: null, tzOffsetMinutes: 0 });
|
||||
assert.equal(again.ok, false);
|
||||
assert.equal((await stateOf(late.baseId)).catchUp?.credit, s.catchUp.credit);
|
||||
// Ansicht: Bauhof bekommt Betrag und Herkunft.
|
||||
const v = await baseView(engine, late.playerId);
|
||||
assert.equal(v.base?.catchUp?.pack, s.catchUp.pack);
|
||||
assert.equal(v.base?.catchUp?.credit, Math.floor(s.catchUp.credit));
|
||||
});
|
||||
|
||||
test("Stündlicher Lauf: Bonus nach Rückstand (Deckel +50 %), Zufluss nur bei Hilfe, nicht beim Spitzenreiter", async () => {
|
||||
await patch(late.baseId, (s) => ({ ...s, buildings: { ...s.buildings, stahlwerk: 4, raffinerie: 2, kraftwerk: 3 }, catchUp: { ...s.catchUp!, credit: 0, lastAtMs: Date.now() - 3600000 } }));
|
||||
const n = await runCatchUp(engine, Date.now(), { force: true });
|
||||
assert.ok(n >= 1);
|
||||
const s = await stateOf(late.baseId);
|
||||
assert.ok(s.catchUp!.ratio! < cu.full, `Verhältnis ${s.catchUp!.ratio}`);
|
||||
assert.equal(s.catchUp!.bonus, cu.cap, "voller Bonus = Deckel 50 %");
|
||||
assert.equal(s.catchUp!.active, true);
|
||||
// Zufluss mit dem Bonus des vorigen Laufs (Startwert 0): erst ab dem nächsten Lauf.
|
||||
await patch(late.baseId, (x) => ({ ...x, catchUp: { ...x.catchUp!, lastAtMs: Date.now() - 3600000 } }));
|
||||
await runCatchUp(engine, Date.now(), { force: true });
|
||||
const s2 = await stateOf(late.baseId);
|
||||
assert.ok(s2.catchUp!.credit > 0, "Zufluss fehlt");
|
||||
assert.ok(s2.catchUp!.earned >= s2.catchUp!.credit - 1e-6);
|
||||
// Ohne force: höchstens einmal je refreshMinutes.
|
||||
assert.equal(await runCatchUp(engine, Date.now()), 0);
|
||||
// Spitzenreiter (Verhältnis ≥ 70 %) bekommt kein Konto.
|
||||
assert.equal((await stateOf(veteran.baseId)).catchUp, undefined);
|
||||
});
|
||||
|
||||
test("Gutschrift bezahlt nur Gebäude: Ausbau zieht zuerst aus ihr, Ausbildung nicht; Abbruch erstattet in die Gutschrift", async () => {
|
||||
await patch(late.baseId, (s) => ({ ...s, resources: { ...ZERO }, resUpdatedAt: Date.now(), buildings: { ...s.buildings, kaserne: 1 }, catchUp: { ...s.catchUp!, credit: 50000 } }));
|
||||
const t = await train(engine, late.playerId, key(), "schuetzen", 1);
|
||||
assert.equal(t.ok, false);
|
||||
assert.equal(!t.ok && t.code, "insufficient_resources");
|
||||
assert.equal((await stateOf(late.baseId)).catchUp!.credit, 50000, "Ausbildung lässt die Gutschrift unberührt");
|
||||
const level = (await stateOf(late.baseId)).buildings.kommandozentrale ?? 0;
|
||||
const u = await upgrade(engine, late.playerId, key(), "kommandozentrale");
|
||||
assert.equal(u.ok, true, JSON.stringify(u));
|
||||
const after = await stateOf(late.baseId);
|
||||
const cost = refValue(upgradeCost("kommandozentrale", level, bal), bal);
|
||||
assert.ok(Math.abs(after.catchUp!.credit - (50000 - cost)) < 1e-6);
|
||||
assert.ok(Object.values(after.resources).every((v) => v < 1), "Lager unberührt");
|
||||
const c = await cancelBuild(engine, late.playerId, key());
|
||||
assert.equal(c.ok, true);
|
||||
const back = await stateOf(late.baseId);
|
||||
assert.ok(back.catchUp!.credit > 50000 - cost, "Abbruch erstattet in die Gutschrift");
|
||||
assert.ok(Object.values(back.resources).every((v) => v < 1), "nichts ins Lager");
|
||||
});
|
||||
|
||||
test("Nicht handelbar und nicht plünderbar: Angebot ohne Lagerbestand abgelehnt, Beute greift nur das Lager", async () => {
|
||||
await patch(late.baseId, (s) => ({ ...s, resources: { ...ZERO }, resUpdatedAt: Date.now(), buildings: { ...s.buildings, hafenkommandantur: 5 }, catchUp: { ...s.catchUp!, credit: 80000 } }));
|
||||
const o = await createOffer(engine, late.playerId, key(), { give: "stahl", giveQty: 100, want: "treibstoff", wantQty: 50, visibility: "public" });
|
||||
assert.equal(o.ok, false);
|
||||
assert.equal(!o.ok && o.code, "funds");
|
||||
const s = await stateOf(late.baseId);
|
||||
const d = defenderFromBase(s, bal);
|
||||
assert.deepEqual(d.resources, s.resources, "Kampf sieht nur das Lager");
|
||||
const side = { before: {}, final: {}, survivors: {}, losses: {} };
|
||||
const report = { attacker: side, defender: side, loot: { stahl: 1000 }, winner: "attacker" } as unknown as BattleReport;
|
||||
const hit = applyDefenseResult(s, report, Date.now(), bal);
|
||||
assert.equal(hit.catchUp?.credit, 80000);
|
||||
});
|
||||
@@ -476,3 +476,5 @@ Umgesetzt mit den empfohlenen Antworten 1a–7a; Zahlen im eigenen Balance-Block
|
||||
einen Spielerhafen) und Kartenblatt zeigen Kopfgeld, Mutfaktor, Paarbremse und Absprache (`social.pvpTarget`);
|
||||
Missionsplanung warnt „Dein Anfängerschutz endet damit“; Kampfbericht nennt Kopfgeld/Mut/Absprache; Verwaltung
|
||||
„Auffällige Paare“ mit „Bericht aus der Wertung nehmen“.
|
||||
|
||||
Fortsetzung in `ENTSCHEIDUNGEN-5.md`.
|
||||
@@ -0,0 +1,57 @@
|
||||
# game-core – Entscheidungen, Teil 5
|
||||
|
||||
Fortsetzung von `ENTSCHEIDUNGEN-4.md`. Verbindlich bleibt `docs/REGELN.md`. Neue Abschnitte bitte hier anhängen.
|
||||
|
||||
## AB. Aufholhilfe (Baugutschrift für kleine Häfen und Spät-Einsteiger)
|
||||
|
||||
Umsetzung der Vorlage `docs/VORLAGE-AUFHOLHILFE.md` (im Haupt-Checkout) mit den Nutzerentscheiden (Messung an Ausbaupunkten, Deckel +50 %
|
||||
statt +100 %, Baugutschrift, Startpaket 15 % ab Tag 8, gilt für KI, keine schnellere Bauzeit). Regeln:
|
||||
`docs/REGELN.md` „Aufholhilfe“; Balance-Block `catchUp`; Kern `game-core/src/catch-up.ts`, Server
|
||||
`engine/src/catch-up.ts`, Rechnung `game-core/sim/aufholhilfe.ts`.
|
||||
|
||||
1. **Kurve:** b = 0,5 × clamp((0,70 − r) / 0,40; 0; 1) – Beginn unter 70 %, linear bis zum Deckel +50 % bei ≤ 30 %
|
||||
(60 % → +12,5 %, 50 % → +25 %, 40 % → +37,5 %). Hysterese wie Vorlage (Wegfall ab 70 %, Wiederbeginn unter 60 %).
|
||||
2. **Konto:** Betrag zum Börsen-Richtwert (Stahl = 1) in `BaseState.catchUp` (eigenes Feld, nicht in `resources`):
|
||||
Lager, Plünderung (`defenderFromBase`/`applyDefenseResult`), Handel, Transport und Kolonie-Fracht sehen es gar nicht.
|
||||
`cloneBase` kopiert es (sonst ginge es bei jedem `settle` verloren). Je Hafen, r je Spieler über alle Häfen.
|
||||
3. **Verbrauch: zuerst, nicht anteilig.** `startUpgrade` verbraucht die Gutschrift vor dem Lager und deckt denselben
|
||||
Anteil jeder Ressource (abgerundet, `splitBuildCost`). Begründung: Die Gutschrift hat keinen anderen Zweck, ihr
|
||||
Zufluss ruht am Höchstbestand (24 h) – „anteilig“ hielte sie unnötig voll und bremste genau die Hilfe; sie ist nicht
|
||||
plünderbar, also gibt es keinen Grund, das Lager zuerst zu leeren. Ein fester Anteil je Ressource verhindert, dass
|
||||
die Gutschrift gezielt nur die knappe Elektronik bezahlt. Der Auftrag merkt sich `credit`; `cancelUpgrade` erstattet
|
||||
diesen Teil (anteilig wie üblich) in die Gutschrift statt ins Lager – sonst würde ein Abbruch Gutschrift in
|
||||
plünder- und handelbare Rohstoffe verwandeln.
|
||||
4. **Leichtgewichtig für den Pi:** Worker-Schritt alle 10 Minuten, rechnet nur alle `refreshMinutes` (60): eine Abfrage
|
||||
`state->'buildings'` aller Häfen, `buildingValue` aus `scoring.ts` (nur gelesen), Median in `server_setting catch_up`.
|
||||
Geschrieben werden nur Häfen mit Konto oder mit Hilfe, je Hafen kurze Transaktion mit `for update` + `jsonb_set`
|
||||
(kein verlorener Verbrauch durch gleichzeitige Bauaufträge). Zufluss mit dem Bonus des vorigen Laufs, höchstens 2 h
|
||||
je Lauf (Worker-Stillstand zahlt nicht nach). Gebäudeproduktion ohne Forschungszuschläge (spart Modifikator-Abfragen).
|
||||
5. **Startpaket** in `chooseBase` (Menschen und KI): ab Saisontag 8 (Tag 1 = Beginn), Median aus dem Zwischenspeicher
|
||||
(höchstens zwei Läufe alt), sonst frisch gerechnet. Einmalig, da nur der erste Hafen über `chooseBase` entsteht
|
||||
(Heimathafen lässt sich nicht aufgeben; Kolonien bekommen nichts).
|
||||
6. **Missbrauch:** kein Neustart möglich (neues Konto nur per Einladung), Median nur aus Häfen ≥ 3 Tage, Gutschrift nur
|
||||
für Gebäude (Rüsten bringt nichts, Bauen beendet die Hilfe von selbst). Die Verwaltung zeigt je Spieler aktiv,
|
||||
Bonus, Bestand und Summe (Statistik → Wirtschaft).
|
||||
7. **Bots** nutzen die Gutschrift automatisch (gleicher `startUpgrade`); ihre Rücklage beim Sparen rechnet nur den
|
||||
Lageranteil (`bots-plan.ts`). Sim-Bot: Gutschrift-Teile zählen nicht als eigene Bauausgaben (Rüstungsanteil).
|
||||
8. **Oberfläche:** Zeile unter der Ressourcenleiste und im Bauhof (Betrag, Herkunft „Aufholhilfe“, Erklärblatt),
|
||||
Kosten im Gebäudeblatt verrechnet („Baugutschrift“ / „aus dem Lager“), Raute „ausbaubar“ nach Abzug der
|
||||
Gutschrift; Handbuch-Kapitel „Aufholhilfe“.
|
||||
|
||||
**Rechnung** (`node packages/game-core/sim/aufholhilfe.ts`; Median = Referenz-Bot 45 % Rüstung, „Spitze“ =
|
||||
Wirtschaftsspieler 25 % Rüstung; Ausbauwert / Median nach 14 Tagen bzw. am Saisonende Tag 42):
|
||||
|
||||
| Einstieg (Saisontag) | ohne Hilfe +14 / Ende | **Paket 15 % + Bonus +50 %** +14 / Ende | Σ Gutschrift | höchstens / Spitze | Vergleich +100 % +14 / Ende |
|
||||
|---|---|---|---|---|---|
|
||||
| 8 | 58 / 96 % | **80 / 105 %** | 18 k | 69 % | 80 / 105 % |
|
||||
| 15 | 35 / 70 % | **66 / 84 %** | 45 k | 55 % | 70 / 87 % |
|
||||
| 22 | 25 / 42 % | **60 / 77 %** | 84 k | 51 % | 70 / 96 % |
|
||||
| 29 | – / 24 % | **– / 76 %** (nach 13 Tagen) | 112 k | 50 % | – / 83 % |
|
||||
|
||||
- Die Baugutschrift wirkt stärker als die Vorlage (dort Rohstoffe, Bonus +100 %: Tag 22 + 14 → 54 %): sie fließt
|
||||
vollständig in Gebäude. Deshalb reicht der halbe Deckel; +100 % brächte vor allem späten Einsteigern mehr
|
||||
(Tag 22: Ende 96 % statt 77 %) und kaum Vorteil sonst.
|
||||
- **Niemand überholt die Spitze:** höchstens 69 % des Ausbaus der Spitze. Der Einsteiger an Tag 8 endet bei 105 % des
|
||||
Medians – die Hilfe endet bei ihm schon nach etwa einer Woche (71 %), den Rest holt er selbst auf, weil der
|
||||
Median-Ausbau gegen Saisonende abflacht (ohne Hilfe 96 %).
|
||||
- Wer von Anfang an mitspielt, bekommt nichts (Σ 0).
|
||||
@@ -399,3 +399,4 @@ der Angreifer 50 % gewinnt; links ohne Würfel wie v1.3, rechts mit):
|
||||
je Typ mit Ø Erfahrung; `veteranStats` in `engine/adminstats.ts`).
|
||||
- Probekampf und freier Simulator rechnen mit den eigenen Modifikatoren (Forschung, Veteranen), das Ziel ohne
|
||||
(Forschung und Erfahrung des Gegners zeigt die Aufklärung nicht).
|
||||
- AB. Aufholhilfe und folgende → `ENTSCHEIDUNGEN-5.md`
|
||||
@@ -0,0 +1,89 @@
|
||||
// Aufholhilfe (Balance-Block catchUp): Wie weit kommt ein Spät-Einsteiger (Start an Saisontag s) mit Baugutschrift?
|
||||
// Bezug „Median“ = Referenz-Bot (Spätspiel, 45 % Rüstung) ab Tag 0. Die Gutschrift fließt stündlich nach Rückstand der
|
||||
// Ausbaupunkte (Kurve wie catchUpBonus, Hysterese, Höchstbestand storeHours) in BaseState.catchUp; der Bot verbraucht sie
|
||||
// über startUpgrade automatisch (nur Gebäude). Startpaket: latePackShare × Median-Ausbauwert am Starttag (ab latePackFromDay).
|
||||
// Aufruf: node packages/game-core/sim/aufholhilfe.ts
|
||||
import { readFileSync } from "node:fs";
|
||||
import type { Balance, BaseState, CatchUpBalance } from "../src/index.ts";
|
||||
import { accrueCatchUp, catchUpBonus, emptyCatchUp, productionRates, upgradeCost } from "../src/index.ts";
|
||||
import { runBot, value } from "./bot.ts";
|
||||
|
||||
const balance = JSON.parse(readFileSync(new URL("../../balance/v1/balance.json", import.meta.url), "utf8")) as Balance;
|
||||
const DAY = 86400000;
|
||||
const HOUR = 3600000;
|
||||
const SEASON = 42;
|
||||
const DAYS = Array.from({ length: SEASON }, (_, i) => i + 1);
|
||||
|
||||
const build = (b: BaseState) => {
|
||||
let s = 0;
|
||||
for (const [id, l] of Object.entries(b.buildings)) for (let i = 0; i < l; i++) s += value(upgradeCost(id, i, balance), balance);
|
||||
return s;
|
||||
};
|
||||
|
||||
const ref = runBot(balance, SEASON, DAYS, 0.45, undefined, undefined, {}, { lateGame: true });
|
||||
const refBuild = [0, ...ref.map((s) => build(s.base))];
|
||||
// „Spitze“: Wirtschaftsspieler mit 25 % Rüstung ab Tag 0 (baut am meisten aus).
|
||||
const top = runBot(balance, SEASON, DAYS, 0.25, undefined, undefined, {}, { lateGame: true });
|
||||
const topBuild = [0, ...top.map((s) => build(s.base))];
|
||||
const refBuildAt = (dayF: number) => {
|
||||
const d = Math.max(0, Math.min(SEASON, dayF));
|
||||
const i = Math.floor(d);
|
||||
const j = Math.min(SEASON, i + 1);
|
||||
return Math.max(1, refBuild[i] + (refBuild[j] - refBuild[i]) * (d - i));
|
||||
};
|
||||
|
||||
interface Variant { label: string; cap: number; pack: number }
|
||||
|
||||
function late(startDay: number, v: Variant, cu0: CatchUpBalance) {
|
||||
const cu: CatchUpBalance = { ...cu0, cap: v.cap };
|
||||
const days = SEASON - startDay;
|
||||
const marks = [...[3, 7, 10, 14, 21].filter((d) => d < days), days];
|
||||
let lastHour = -1;
|
||||
let total = 0;
|
||||
let first = true;
|
||||
const onStep = (b: BaseState, t: number): BaseState => {
|
||||
if (first) {
|
||||
first = false;
|
||||
// Startpaket: Saisontag (1 = erster Tag) des Einstiegs ab latePackFromDay.
|
||||
const pack = startDay + 1 >= cu.latePackFromDay ? v.pack * refBuild[startDay] : 0;
|
||||
total += pack;
|
||||
return { ...b, catchUp: { ...emptyCatchUp(t), credit: pack, pack } };
|
||||
}
|
||||
const hour = Math.floor(t / HOUR);
|
||||
if (hour === lastHour || v.cap <= 0) return b;
|
||||
lastHour = hour;
|
||||
const dayG = startDay + t / DAY;
|
||||
const prev = b.catchUp ?? emptyCatchUp(t);
|
||||
// Median zählt erst Spieler mit Hafen ≥ minBaseAgeDays; der Referenz-Bot ist von Anfang an dabei.
|
||||
const ratio = build(b) / refBuildAt(dayG);
|
||||
const perHour = value(productionRates(b, balance).buildingPerHour, balance);
|
||||
const acc = accrueCatchUp(prev, perHour, t, cu, Math.floor(dayG) + 1 < cu.stopDay);
|
||||
total += acc.earned - prev.earned;
|
||||
const { bonus, active } = catchUpBonus(ratio, cu, b.catchUp ? prev : null);
|
||||
return { ...b, catchUp: { ...acc, bonus, active, ratio } };
|
||||
};
|
||||
const snaps = runBot(balance, days, marks, 0.45, undefined, onStep, {}, { lateGame: true });
|
||||
return { snaps, total, days };
|
||||
}
|
||||
|
||||
const cu = balance.catchUp!;
|
||||
const variants: Variant[] = [
|
||||
{ label: "ohne Hilfe", cap: 0, pack: 0 },
|
||||
{ label: "Paket 15 % allein", cap: 0, pack: cu.latePackShare },
|
||||
{ label: `Bonus bis +${Math.round(cu.cap * 100)} % allein`, cap: cu.cap, pack: 0 },
|
||||
{ label: `Paket 15 % + Bonus bis +${Math.round(cu.cap * 100)} % (gewählt)`, cap: cu.cap, pack: cu.latePackShare },
|
||||
{ label: "Vergleich: Paket 15 % + Bonus bis +100 %", cap: 1, pack: cu.latePackShare },
|
||||
];
|
||||
|
||||
console.log(`Referenz (Median-Ersatz) Ausbauwert: ${[7, 14, 21, 28, 35, 42].map((d) => `T${d} ${Math.round(refBuild[d] / 1000)}k`).join(", ")}`);
|
||||
console.log(`Spitze (25 % Rüstung) Ausbauwert: ${[7, 14, 21, 28, 35, 42].map((d) => `T${d} ${Math.round(topBuild[d] / 1000)}k`).join(", ")}`);
|
||||
console.log(`Kurve: Beginn unter ${cu.from * 100} %, voll (+${cu.cap * 100} %) ab ≤ ${cu.full * 100} %, Hysterese ${cu.resumeBelow * 100} %, Höchstbestand ${cu.storeHours} h, Zufluss bis Saisontag ${cu.stopDay}`);
|
||||
for (const s of [0, 7, 14, 21, 28]) {
|
||||
console.log(`\nEinstieg nach ${s} Tagen (Saisontag ${s + 1}): Ausbauwert / Median nach x Tagen, Saisonende = Tag ${SEASON}; Σ Gutschrift (Richtwert)`);
|
||||
for (const v of variants) {
|
||||
const r = late(s, v, cu);
|
||||
const cells = r.snaps.map((x) => `${x.day === r.days ? "Ende" : `+${x.day}`}: ${Math.round((build(x.base) / refBuild[s + x.day]) * 100)} %`);
|
||||
const peak = Math.max(...r.snaps.map((x) => build(x.base) / topBuild[s + x.day]));
|
||||
console.log(` ${v.label.padEnd(44)}${cells.map((x) => x.padEnd(12)).join("")} max/Spitze ${Math.round(peak * 100)} % Σ ${Math.round(r.total / 1000)}k`);
|
||||
}
|
||||
}
|
||||
@@ -203,7 +203,8 @@ export function runBot(
|
||||
const r = startUpgrade(base, id, t, balance);
|
||||
if (r.ok) {
|
||||
base = r.base;
|
||||
spentBuild += value(cost, balance);
|
||||
// Aufholhilfe: aus der Baugutschrift bezahlte Teile sind keine eigenen Ausgaben (Rüstungsanteil unverzerrt).
|
||||
spentBuild += value(cost, balance) - value(r.order.credit ?? {}, balance);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { buildingLevel, hasResources, settle, subtractResources } from "./econom
|
||||
import type { Modifiers } from "./modifiers.ts";
|
||||
import { modValue } from "./modifiers.ts";
|
||||
import { homeOnlyBlocked } from "./expansion.ts";
|
||||
import { buildCredit, splitBuildCost } from "./catch-up.ts";
|
||||
|
||||
/** Erstes fehlendes Voraussetzungsgebäude (id, nötige Stufe) für den Bau von `buildingId`, sonst null. */
|
||||
export function missingRequirement(base: BaseState, buildingId: string, balance: Balance): { id: string; level: number } | null {
|
||||
@@ -86,7 +87,9 @@ export function upgradeDurationMs(buildingId: string, targetLevel: number, balan
|
||||
/**
|
||||
* Reiht einen Ausbau in die Bauschlange ein (höchstens building.queueSlots Aufträge). Die Zielstufe
|
||||
* berücksichtigt bereits eingereihte Aufträge desselben Gebäudes; die Kosten werden sofort bezahlt.
|
||||
* Der Auftrag beginnt, wenn der vorige fertig ist (frühestens jetzt).
|
||||
* Der Auftrag beginnt, wenn der vorige fertig ist (frühestens jetzt). Aufholhilfe: Eine Baugutschrift (catchUp.credit)
|
||||
* wird zuerst verbraucht (deckt denselben Anteil jeder Ressource), den Rest zahlt das Lager; der Auftrag merkt sich den
|
||||
* Gutschrift-Anteil (order.credit), damit ein Abbruch ihn in die Gutschrift statt ins Lager erstattet.
|
||||
* Codes: unknown_building, home_only (nur im Heimathafen, z. B. Forschungsamt in einer Kolonie), queue_full, max_level,
|
||||
* command_cap, building_requires (Voraussetzung fehlt, z. B. Startrampe), insufficient_resources.
|
||||
*/
|
||||
@@ -106,8 +109,12 @@ export function startUpgrade(
|
||||
if (level + 1 > maxAllowedLevel(base, buildingId, balance)) return { ok: false, code: "command_cap" };
|
||||
const next = settle(base, nowMs, balance, mods);
|
||||
const cost = upgradeCost(buildingId, level, balance);
|
||||
if (!hasResources(next.resources, cost)) return { ok: false, code: "insufficient_resources" };
|
||||
next.resources = subtractResources(next.resources, cost);
|
||||
const credit = buildCredit(next);
|
||||
const pay = credit > 0 ? splitBuildCost(cost, credit, balance) : null;
|
||||
const fromStock = pay ? pay.fromStock : cost;
|
||||
if (!hasResources(next.resources, fromStock)) return { ok: false, code: "insufficient_resources" };
|
||||
next.resources = subtractResources(next.resources, fromStock);
|
||||
if (pay && pay.used > 0) next.catchUp = { ...next.catchUp!, credit: Math.max(0, credit - pay.used) };
|
||||
const last = next.buildQueue[next.buildQueue.length - 1];
|
||||
const startedAt = last === undefined ? nowMs : Math.max(nowMs, last.finishesAt);
|
||||
const order: BuildOrder = {
|
||||
@@ -115,6 +122,7 @@ export function startUpgrade(
|
||||
targetLevel: level + 1,
|
||||
startedAt,
|
||||
finishesAt: startedAt + upgradeDurationMs(buildingId, level + 1, balance, mods),
|
||||
...(pay && pay.used > 0 ? { credit: pay.fromCredit } : {}),
|
||||
};
|
||||
next.buildQueue = [...next.buildQueue, order];
|
||||
return { ok: true, base: next, order: { ...order } };
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
// Aufholhilfe (Balance-Block catchUp, docs/REGELN.md „Aufholhilfe“): Häfen, deren Ausbau weit unter dem Median liegt,
|
||||
// bekommen eine Baugutschrift. Sie bezahlt nur Gebäudestufen, liegt in einem eigenen Konto des Hafens (BaseState.catchUp),
|
||||
// zählt nicht zum Lager und ist weder plünderbar noch handelbar oder transportierbar. Reine Funktionen; den stündlichen
|
||||
// Lauf (Median, Rückstand, Zufluss) und das Startpaket macht der Server (engine/catch-up.ts).
|
||||
import type { Balance, BaseState, ResourceMap } from "./types.ts";
|
||||
|
||||
export interface CatchUpBalance {
|
||||
/** Bonus beginnt unter diesem Verhältnis Ausbaupunkte / Median (0,70). */
|
||||
from: number;
|
||||
/** Voller Bonus ab diesem Verhältnis und darunter (0,30). */
|
||||
full: number;
|
||||
/** Deckel des Bonus als Anteil der Gebäudeproduktion (0,5 = +50 %). */
|
||||
cap: number;
|
||||
/** Hysterese: nach dem Wegfall (Verhältnis ≥ from) erst wieder unter diesem Verhältnis (0,60). */
|
||||
resumeBelow: number;
|
||||
/** Zum Median zählen nur Spieler, deren erster Hafen mindestens so viele Tage alt ist (3). */
|
||||
minBaseAgeDays: number;
|
||||
/** Höchstbestand der Gutschrift in Stunden Zufluss (24); darüber ruht der Zufluss. */
|
||||
storeHours: number;
|
||||
/** Ab diesem Saisontag (0 = erster Tag) kein Zufluss mehr (40). */
|
||||
stopDay: number;
|
||||
/** Startpaket: wer seinen ersten Hafen ab diesem Saisontag gründet (8) … */
|
||||
latePackFromDay: number;
|
||||
/** … bekommt diesen Anteil des Median-Ausbauwerts als Baugutschrift (0,15). */
|
||||
latePackShare: number;
|
||||
/** Abstand der Läufe im Worker in Minuten (60); so lange gilt auch der zwischengespeicherte Median. */
|
||||
refreshMinutes: number;
|
||||
/** Höchstens so viele Stunden Zufluss je Lauf (2), falls der Worker eine Weile stand. */
|
||||
maxCatchUpHours: number;
|
||||
}
|
||||
|
||||
/** Konto der Aufholhilfe im Hafenzustand. Beträge zum Börsen-Richtwert (market.refPrice, Stahl = 1). */
|
||||
export interface CatchUpState {
|
||||
/** Bestand der Baugutschrift. */
|
||||
credit: number;
|
||||
/** Aktueller Bonus (Anteil der Gebäudeproduktion, 0 bis cap). */
|
||||
bonus: number;
|
||||
/** Zuletzt gemessenes Verhältnis eigene Ausbaupunkte / Median (null: noch kein Median). */
|
||||
ratio: number | null;
|
||||
/** Hysterese: Hilfe läuft (erst unter resumeBelow wieder an, endet ab from). */
|
||||
active: boolean;
|
||||
/** Zeitpunkt des letzten Zuflusses (Worker). */
|
||||
lastAtMs: number;
|
||||
/** Summe aller Zuflüsse aus dem Bonus in dieser Saison. */
|
||||
earned: number;
|
||||
/** Startpaket für Spät-Einsteiger (Betrag), falls erhalten. */
|
||||
pack?: number;
|
||||
}
|
||||
|
||||
export function catchUpOf(balance: Balance): CatchUpBalance | null {
|
||||
return balance.catchUp ?? null;
|
||||
}
|
||||
|
||||
/** Wert einer Ressourcenmenge zum Börsen-Richtwert (Stahl = 1). */
|
||||
export function refValue(m: ResourceMap, balance: Balance): number {
|
||||
const price = balance.market.refPrice as Record<string, number>;
|
||||
let s = 0;
|
||||
for (const [r, v] of Object.entries(m)) s += (v || 0) * (price[r] ?? 1);
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Bonus nach Rückstand: cap × clamp((from − r) / (from − full); 0; 1). */
|
||||
export function catchUpCurve(ratio: number, cu: CatchUpBalance): number {
|
||||
const t = (cu.from - ratio) / Math.max(1e-9, cu.from - cu.full);
|
||||
return cu.cap * Math.max(0, Math.min(1, t));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bonus mit Hysterese: läuft die Hilfe, endet sie erst bei r ≥ from; ruht sie, beginnt sie erst unter resumeBelow.
|
||||
* Erster Lauf (keine Vorgeschichte oder noch keine Messung) wie „ruht nicht“: unter from beginnt sie sofort.
|
||||
*/
|
||||
export function catchUpBonus(ratio: number | null, cu: CatchUpBalance, prev?: Pick<CatchUpState, "active" | "ratio"> | null): { bonus: number; active: boolean } {
|
||||
if (ratio === null || !Number.isFinite(ratio)) return { bonus: 0, active: false };
|
||||
// Ohne frühere Messung (neues Konto, z. B. nur Startpaket) gilt die Hilfe als „nicht ruhend“.
|
||||
const wasActive = prev && prev.ratio !== null ? prev.active : true;
|
||||
const active = ratio < (wasActive ? cu.from : cu.resumeBelow);
|
||||
return { bonus: active ? catchUpCurve(ratio, cu) : 0, active };
|
||||
}
|
||||
|
||||
/** Median einer Zahlenliste (leer: null). */
|
||||
export function median(values: number[]): number | null {
|
||||
if (values.length === 0) return null;
|
||||
const v = [...values].sort((a, b) => a - b);
|
||||
const m = Math.floor(v.length / 2);
|
||||
return v.length % 2 ? v[m] : (v[m - 1] + v[m]) / 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Aufteilung der Baukosten: Die Gutschrift wird zuerst verbraucht und deckt denselben Anteil jeder Ressource
|
||||
* (abgerundet, damit nie mehr als der Bestand verbraucht wird); den Rest zahlt das Lager.
|
||||
*/
|
||||
export function splitBuildCost(cost: ResourceMap, credit: number, balance: Balance): { fromCredit: ResourceMap; fromStock: ResourceMap; used: number } {
|
||||
const total = refValue(cost, balance);
|
||||
const share = credit > 0 && total > 0 ? Math.min(1, credit / total) : 0;
|
||||
const fromCredit: ResourceMap = {};
|
||||
const fromStock: ResourceMap = {};
|
||||
for (const [r, v] of Object.entries(cost)) {
|
||||
const c = share >= 1 ? v : Math.floor(v * share);
|
||||
if (c > 0) fromCredit[r] = c;
|
||||
fromStock[r] = v - c;
|
||||
}
|
||||
return { fromCredit, fromStock, used: refValue(fromCredit, balance) };
|
||||
}
|
||||
|
||||
/** Bestand der Baugutschrift eines Hafens (0 ohne Konto). */
|
||||
export function buildCredit(base: BaseState): number {
|
||||
return Math.max(0, base.catchUp?.credit ?? 0);
|
||||
}
|
||||
|
||||
/** Neues Konto mit Startwerten (Stand ohne Messung). */
|
||||
export function emptyCatchUp(nowMs: number): CatchUpState {
|
||||
return { credit: 0, bonus: 0, ratio: null, active: false, lastAtMs: nowMs, earned: 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Zufluss eines Laufs: bonus × Gebäudeproduktion (Wert je Stunde) × Stunden (höchstens maxCatchUpHours). Der Bestand
|
||||
* wächst höchstens bis storeHours × Zufluss je Stunde; darüber ruht der Zufluss (ein Startpaket darf darüber liegen).
|
||||
*/
|
||||
export function accrueCatchUp(state: CatchUpState, buildingValuePerHour: number, nowMs: number, cu: CatchUpBalance, flowing = true): CatchUpState {
|
||||
const hours = Math.max(0, Math.min(cu.maxCatchUpHours, (nowMs - state.lastAtMs) / 3600000));
|
||||
const perHour = flowing ? state.bonus * Math.max(0, buildingValuePerHour) : 0;
|
||||
const ceiling = cu.storeHours * perHour;
|
||||
const add = Math.max(0, Math.min(perHour * hours, ceiling - state.credit));
|
||||
return { ...state, credit: state.credit + add, earned: state.earned + add, lastAtMs: nowMs };
|
||||
}
|
||||
@@ -42,6 +42,8 @@ export function cloneBase(base: BaseState): BaseState {
|
||||
...(base.colony ? { colony: { ...base.colony } } : {}),
|
||||
// Lagebild Stufe 3: gestartete Satelliten (sonst verschwänden sie beim nächsten settle).
|
||||
...(base.satellites ? { satellites: base.satellites.map((s) => ({ ...s, ...(s.last ? { last: { ...s.last } } : {}) })) } : {}),
|
||||
// Aufholhilfe: Konto der Baugutschrift.
|
||||
...(base.catchUp ? { catchUp: { ...base.catchUp } } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -32,3 +32,4 @@ export * from "./intel-sat.ts"; // Lagebild Stufe 3: Satelliten, Tarnnetze, Stö
|
||||
export * from "./route-position.ts"; // Seewege: Position unterwegs (Route, Rückruf, Patrouille, Kampagne)
|
||||
export * from "./raid-plan.ts"; // Einstieg: kleinster siegreicher Verband gegen ein Nest
|
||||
export * from "./pvp.ts"; // Spieler gegen Spieler: Kopfgeld, Mutfaktor, Paarbremse
|
||||
export * from "./catch-up.ts"; // Aufholhilfe: Baugutschrift für kleine Häfen und Spät-Einsteiger
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
} from "./types.ts";
|
||||
import { addResources, bunkerProtection, buildingLevel, settle } from "./economy.ts";
|
||||
import { upgradeCost } from "./buildings.ts";
|
||||
import { emptyCatchUp, refValue } from "./catch-up.ts";
|
||||
import { trainingCost } from "./units.ts";
|
||||
import { applyDefeatShield } from "./protection.ts";
|
||||
import { battleVeterancy } from "./veterans.ts";
|
||||
@@ -268,13 +269,22 @@ export function cancelUpgrade(
|
||||
balance: Balance,
|
||||
index = 0,
|
||||
mods?: Modifiers,
|
||||
): Result<{ base: BaseState; refund: ResourceMap; removed: BuildOrder[] }> {
|
||||
): Result<{ base: BaseState; refund: ResourceMap; removed: BuildOrder[]; creditRefund: number }> {
|
||||
const order = Number.isInteger(index) && index >= 0 ? base.buildQueue[index] : undefined;
|
||||
if (order === undefined) return { ok: false, code: "no_order" };
|
||||
if (nowMs >= order.finishesAt) return { ok: false, code: "already_finished" };
|
||||
const cost = upgradeCost(order.buildingId, order.targetLevel - 1, balance);
|
||||
const share = order.startedAt <= nowMs ? refundShare(order.startedAt, order.finishesAt, nowMs) : 1;
|
||||
let refund = scaled(cost, share);
|
||||
// Aufholhilfe: der aus der Baugutschrift bezahlte Teil geht anteilig in die Gutschrift zurück, nicht ins Lager.
|
||||
let creditRefund = 0;
|
||||
const paid = (o: BuildOrder, part: number): ResourceMap => {
|
||||
const cost = upgradeCost(o.buildingId, o.targetLevel - 1, balance);
|
||||
if (o.credit) {
|
||||
for (const [r, v] of Object.entries(o.credit)) cost[r] = Math.max(0, (cost[r] ?? 0) - v);
|
||||
creditRefund += refValue(o.credit, balance) * part;
|
||||
}
|
||||
return scaled(cost, part);
|
||||
};
|
||||
let refund = paid(order, share);
|
||||
const removed: BuildOrder[] = [{ ...order }];
|
||||
|
||||
const next = settle(base, nowMs, balance, mods);
|
||||
@@ -290,7 +300,7 @@ export function cancelUpgrade(
|
||||
: Math.min(balance.building.maxLevel, (levels.kommandozentrale ?? 0) + balance.building.levelCapAboveCommand);
|
||||
if (o.targetLevel !== level + 1 || o.targetLevel > cap) {
|
||||
// Nicht mehr gültig: noch nicht begonnen, also voll erstatten.
|
||||
refund = addResources(refund, upgradeCost(o.buildingId, o.targetLevel - 1, balance));
|
||||
refund = addResources(refund, paid(o, 1));
|
||||
removed.push({ ...o });
|
||||
return;
|
||||
}
|
||||
@@ -306,7 +316,8 @@ export function cancelUpgrade(
|
||||
});
|
||||
next.buildQueue = queue;
|
||||
next.resources = addResources(next.resources, refund);
|
||||
return { ok: true, base: next, refund, removed };
|
||||
if (creditRefund > 0) next.catchUp = { ...(next.catchUp ?? emptyCatchUp(nowMs)), credit: (next.catchUp?.credit ?? 0) + creditRefund };
|
||||
return { ok: true, base: next, refund, removed, creditRefund };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -226,6 +226,8 @@ export interface Balance {
|
||||
intel?: import("./intel.ts").IntelBalance;
|
||||
/** Spieler gegen Spieler (Kopfgeld, Mutfaktor, Paarbremse; pvp.ts); fehlt es, zählt jeder Kampf ohne diese Faktoren. */
|
||||
pvp?: import("./pvp.ts").PvpBalance;
|
||||
/** Aufholhilfe (catch-up.ts): Baugutschrift für Häfen weit unter dem Median; fehlt es, gibt es keine. */
|
||||
catchUp?: import("./catch-up.ts").CatchUpBalance;
|
||||
}
|
||||
|
||||
/** Wertung (v1.24). Punkte bewerten Ressourcen zum Börsen-Richtpreis (market.refPrice). */
|
||||
@@ -273,6 +275,8 @@ export interface BuildOrder {
|
||||
targetLevel: number;
|
||||
startedAt: number;
|
||||
finishesAt: number;
|
||||
/** Aufholhilfe: aus der Baugutschrift bezahlter Teil der Kosten (Abbruch erstattet ihn in die Gutschrift zurück). */
|
||||
credit?: ResourceMap;
|
||||
}
|
||||
|
||||
export interface TrainingOrder {
|
||||
@@ -317,6 +321,8 @@ export interface BaseState {
|
||||
colony?: { foundedAtMs: number };
|
||||
/** Lagebild Stufe 3 (v1.23, intel-sat.ts): von hier gestartete Satelliten (abgelaufene räumt der Server). */
|
||||
satellites?: import("./intel-sat.ts").SatelliteState[];
|
||||
/** Aufholhilfe (catch-up.ts): Konto der Baugutschrift; zählt nicht zum Lager, nicht plünder- oder handelbar. */
|
||||
catchUp?: import("./catch-up.ts").CatchUpState;
|
||||
}
|
||||
|
||||
export interface ProductionInfo {
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
// Aufholhilfe: Kurve, Deckel, Wegfall (Hysterese), Baugutschrift beim Bauen und beim Abbruch.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
accrueCatchUp,
|
||||
cancelUpgrade,
|
||||
catchUpBonus,
|
||||
catchUpCurve,
|
||||
emptyCatchUp,
|
||||
median,
|
||||
refValue,
|
||||
settle,
|
||||
splitBuildCost,
|
||||
startUpgrade,
|
||||
startTraining,
|
||||
upgradeCost,
|
||||
type CatchUpBalance,
|
||||
} from "../src/index.ts";
|
||||
import { HOUR, T0, approx, loadBalance, makeBase } from "./helpers.ts";
|
||||
|
||||
const balance = loadBalance();
|
||||
const cu = balance.catchUp as CatchUpBalance;
|
||||
|
||||
test("Balance: Deckel +50 %, Beginn unter 70 %, voll ab 30 %, Startpaket 15 % ab Tag 8", () => {
|
||||
assert.equal(cu.cap, 0.5);
|
||||
assert.equal(cu.from, 0.7);
|
||||
assert.equal(cu.full, 0.3);
|
||||
assert.equal(cu.latePackFromDay, 8);
|
||||
assert.equal(cu.latePackShare, 0.15);
|
||||
});
|
||||
|
||||
test("Kurve: linear von 0 (70 %) bis zum Deckel 50 % (≤ 30 %)", () => {
|
||||
const at = (r: number) => catchUpCurve(r, cu);
|
||||
assert.equal(at(0.7), 0);
|
||||
assert.equal(at(0.9), 0);
|
||||
assert.ok(approx(at(0.6), 0.125));
|
||||
assert.ok(approx(at(0.5), 0.25));
|
||||
assert.ok(approx(at(0.4), 0.375));
|
||||
assert.ok(approx(at(0.3), 0.5));
|
||||
assert.ok(approx(at(0), 0.5), "nie über den Deckel");
|
||||
});
|
||||
|
||||
test("Wegfall ab 70 %, Wiederbeginn erst unter 60 % (Hysterese)", () => {
|
||||
assert.deepEqual(catchUpBonus(null, cu, null), { bonus: 0, active: false });
|
||||
// Erste Messung unter 70 %: Hilfe beginnt sofort.
|
||||
assert.equal(catchUpBonus(0.65, cu, null).active, true);
|
||||
const on = { active: true, ratio: 0.5 };
|
||||
const off = { active: false, ratio: 0.8 };
|
||||
// Konto ohne Messung (nur Startpaket): wie erste Messung.
|
||||
assert.equal(catchUpBonus(0.65, cu, { active: false, ratio: null }).active, true);
|
||||
assert.equal(catchUpBonus(0.69, cu, on).active, true);
|
||||
assert.equal(catchUpBonus(0.7, cu, on).active, false);
|
||||
assert.deepEqual(catchUpBonus(0.65, cu, off), { bonus: 0, active: false });
|
||||
const back = catchUpBonus(0.55, cu, off);
|
||||
assert.equal(back.active, true);
|
||||
assert.ok(approx(back.bonus, 0.5 * (0.15 / 0.4)));
|
||||
});
|
||||
|
||||
test("Median: gerade und ungerade Anzahl, leer", () => {
|
||||
assert.equal(median([]), null);
|
||||
assert.equal(median([5, 1, 3]), 3);
|
||||
assert.equal(median([4, 1, 3, 2]), 2.5);
|
||||
});
|
||||
|
||||
test("Zufluss: Bonus × Gebäudeproduktion je Stunde, gedeckelt auf storeHours, höchstens maxCatchUpHours", () => {
|
||||
const s = { ...emptyCatchUp(T0), bonus: 0.5 };
|
||||
const a = accrueCatchUp(s, 1000, T0 + HOUR, cu);
|
||||
assert.ok(approx(a.credit, 500));
|
||||
assert.ok(approx(a.earned, 500));
|
||||
// Worker stand 10 Stunden: höchstens maxCatchUpHours.
|
||||
assert.ok(approx(accrueCatchUp(s, 1000, T0 + 10 * HOUR, cu).credit, 500 * cu.maxCatchUpHours));
|
||||
// Höchstbestand erreicht: Zufluss ruht.
|
||||
const full = accrueCatchUp({ ...s, credit: 24 * 500 }, 1000, T0 + HOUR, cu);
|
||||
assert.equal(full.credit, 24 * 500);
|
||||
// Ab stopDay (flowing = false) kein Zufluss.
|
||||
assert.equal(accrueCatchUp(s, 1000, T0 + HOUR, cu, false).credit, 0);
|
||||
});
|
||||
|
||||
test("Aufteilung: Gutschrift zuerst, gleicher Anteil jeder Ressource, nie mehr als der Bestand", () => {
|
||||
const cost = { stahl: 1000, treibstoff: 200, elektronik: 100, proviant: 0 };
|
||||
const total = refValue(cost, balance); // 1000 + 360 + 300 = 1660
|
||||
const half = splitBuildCost(cost, total / 2, balance);
|
||||
assert.deepEqual(half.fromCredit, { stahl: 500, treibstoff: 100, elektronik: 50 });
|
||||
assert.deepEqual(half.fromStock, { stahl: 500, treibstoff: 100, elektronik: 50, proviant: 0 });
|
||||
assert.ok(half.used <= total / 2 + 1e-9);
|
||||
const all = splitBuildCost(cost, 1e9, balance);
|
||||
assert.deepEqual(all.fromStock, { stahl: 0, treibstoff: 0, elektronik: 0, proviant: 0 });
|
||||
assert.ok(approx(all.used, total));
|
||||
assert.equal(splitBuildCost(cost, 0, balance).used, 0);
|
||||
});
|
||||
|
||||
test("Ausbau verbraucht die Gutschrift zuerst; der Rest kommt aus dem Lager", () => {
|
||||
const cost = upgradeCost("stahlwerk", 0, balance);
|
||||
const base = makeBase(balance, { resources: { stahl: 0, treibstoff: 0, elektronik: 0, proviant: 0 }, catchUp: { ...emptyCatchUp(T0), credit: 100000 } });
|
||||
const r = startUpgrade(base, "stahlwerk", T0, balance);
|
||||
assert.ok(r.ok);
|
||||
assert.ok(approx(r.base.catchUp!.credit, 100000 - refValue(cost, balance)));
|
||||
assert.deepEqual(r.order.credit, Object.fromEntries(Object.entries(cost).filter(([, v]) => v > 0)));
|
||||
// Ohne Lager und ohne Gutschrift: abgelehnt.
|
||||
const poor = makeBase(balance, { resources: { stahl: 0, treibstoff: 0, elektronik: 0, proviant: 0 } });
|
||||
assert.equal(startUpgrade(poor, "stahlwerk", T0, balance).ok, false);
|
||||
});
|
||||
|
||||
test("Gutschrift bezahlt keine Einheiten", () => {
|
||||
const base = makeBase(balance, {
|
||||
buildings: { kaserne: 1 },
|
||||
resources: { stahl: 0, treibstoff: 0, elektronik: 0, proviant: 0 },
|
||||
catchUp: { ...emptyCatchUp(T0), credit: 1e6 },
|
||||
});
|
||||
const r = startTraining(base, "schuetzen", 1, T0, balance);
|
||||
assert.equal(r.ok, false);
|
||||
assert.equal(!r.ok && r.code, "insufficient_resources");
|
||||
});
|
||||
|
||||
test("Abbruch erstattet den Gutschrift-Anteil in die Gutschrift, nicht ins Lager", () => {
|
||||
const cost = upgradeCost("stahlwerk", 0, balance);
|
||||
const base = makeBase(balance, { resources: { stahl: 0, treibstoff: 0, elektronik: 0, proviant: 0 }, catchUp: { ...emptyCatchUp(T0), credit: 5000 } });
|
||||
const up = startUpgrade(base, "stahlwerk", T0, balance);
|
||||
assert.ok(up.ok);
|
||||
// Zweiter Auftrag wartet: voller Abbruch.
|
||||
const up2 = startUpgrade(up.base, "stahlwerk", T0, balance);
|
||||
assert.ok(up2.ok);
|
||||
const c = cancelUpgrade(up2.base, T0, balance, 1);
|
||||
assert.ok(c.ok);
|
||||
assert.ok(approx(c.creditRefund, refValue(upgradeCost("stahlwerk", 1, balance), balance)));
|
||||
assert.deepEqual(Object.values(c.refund).filter((v) => v > 0), [], "nichts ins Lager");
|
||||
assert.ok(approx(c.base.catchUp!.credit, 5000 - refValue(cost, balance)));
|
||||
const stahl = settle(up2.base, T0, balance).resources.stahl;
|
||||
assert.equal(c.base.resources.stahl, stahl);
|
||||
});
|
||||
|
||||
test("Konto übersteht das Fortschreiben (settle) und zählt nicht zum Lager", () => {
|
||||
const base = makeBase(balance, { catchUp: { ...emptyCatchUp(T0), credit: 1234 } });
|
||||
const s = settle(base, T0 + 5 * HOUR, balance);
|
||||
assert.equal(s.catchUp?.credit, 1234);
|
||||
assert.equal(Object.values(s.resources).includes(1234), false);
|
||||
});
|
||||
Reference in new issue
Block a user