mirror of
https://github.com/db9979/tidefront.git
synced 2026-12-06 04:44:09 +01:00
Mehrere Häfen P1: Gründung und Verlegung (Kern, Server, Balance v1.11)
- game-core expansion.ts: allowedBases, foundingBlocker, createColony, colonyProtection (Anfängerschutz erbt, 24 h Gründungsschutz), mergeVeterancy; Missionsarten gruendung/verlegung in planMission (Kolonieschiff nur hin, Verlegung nur Hinfahrt); Forschungsamt in Kolonie gesperrt (home_only), Kolonieschiff ab Hafenkommandantur 6 (harbor_level) - Balance v1.11: Block expansion, Einheit kolonieschiff, Erfolg Kolonist; sim/expansion.ts (Amortisation 3 Tage), ENTSCHEIDUNGEN Abschnitt K - Server: launchExpansion/previewExpansion, Ankunft mit Wettlauf über base_field, Geleit kehrt heim, raid_launch nach 48 h; Verlegung mit Veteranen und Admiral; Transport in eigenen Hafen erlaubt - Regeln: docs/REGELN-EXPANSION.md; Tests Kern und Server
This commit is contained in:
1 parent
60d080b6c5
commit
dfd2155e9a
22 files changed
+1060
-57
No files matched your search
@@ -0,0 +1,52 @@
|
||||
# Mehrere Häfen (Welle 3 „Expansion“, Teil 2)
|
||||
|
||||
Teil der Regeln (`docs/REGELN.md`). Werte im Balance-Block `expansion`; fehlt er, gibt es keine Außenposten.
|
||||
Begründung und Simulation: `packages/game-core/ENTSCHEIDUNGEN.md`, Abschnitt K, und `sim/expansion.ts`.
|
||||
|
||||
## Häfen je Spieler
|
||||
|
||||
- Der erste Hafen (Saisonbeginn, „Hafen wählen“) ist der **Heimathafen**; weitere Häfen sind **Kolonien**.
|
||||
- Erlaubt sind `1 + Anzahl der Stufen in unlockCommandLevels (8, 14), die die Kommandozentrale des Heimathafens
|
||||
erreicht hat`, höchstens `maxBases` (3). Laufende Gründungen zählen mit.
|
||||
- Spielerweit bleiben Forschung (im Heimathafen geführt; Kolonien nutzen deren Stufen), Kredite, Erfolge, Allianz,
|
||||
Rangliste (Summe aller Häfen) und die Nachtschild-Einstellung. Je Hafen: Ressourcen, Gebäude, Bauschlange,
|
||||
Ausbildung, Einheiten, Veteranen, Missionsplätze, Schutzzustand.
|
||||
- Gebäude aus `homeOnlyBuildings` (Forschungsamt) gibt es nur im Heimathafen (Kolonie: Fehler `home_only`).
|
||||
- Häfen gehen nicht durch Eroberung verloren. Zum Saisonende werden alle Häfen gelöscht; der erste Hafen der neuen
|
||||
Saison ist wieder der Heimathafen.
|
||||
|
||||
## Kolonieschiff
|
||||
|
||||
- Bau in der Werft ab Stufe `requiresLevel` (6) und Hafenkommandantur ab `harborLevelForShip` (6, sonst
|
||||
`harbor_level`). Höchstzahl `maxPerLevel` je Werftstufe (0,2: ein Schiff bei Werft 6–9, zwei ab 10).
|
||||
- Langsam (30 km/h), unbewaffnet, Ladung 3000, Unterhalt 6 Proviant/h. Es wird bei der Gründung **verbraucht**.
|
||||
|
||||
## Gründung (Missionsart „gruendung“)
|
||||
|
||||
- Ziel: ein **Küstenfeld** ohne Hafen, Piratennest, Handelshafen und Rohstofffeld; mindestens `minDistanceHex` (4)
|
||||
Felder von fremden und `minDistanceOwnHex` (3) Felder von eigenen Häfen; höchstens `maxRangeKm` (900 km) vom
|
||||
Heimathafen entfernt.
|
||||
- Verband: **genau ein** Kolonieschiff, beliebiges Geleit erlaubt; Ladung bis zur Ladekapazität des Verbands
|
||||
(Startgüter). Treibstoff: Kolonieschiff nur hin, Geleit hin und zurück. Belegt einen Missionsplatz.
|
||||
- Bei Ankunft wird das Feld erneut geprüft. Gewinnt ein anderer Spieler den Wettlauf um dasselbe Feld (oder ist es
|
||||
nicht mehr frei), gibt es den Bericht „Gründung gescheitert: …“ und der ganze Verband kehrt mit Ladung heim.
|
||||
- Sonst entsteht der neue Hafen „<Spielername> II“ (bzw. III): Startbestand `startResources` (1000 Stahl,
|
||||
500 Treibstoff, 250 Elektronik, 500 Proviant) plus Ladung, alle Gebäude auf Stufe 0. Das Kolonieschiff ist
|
||||
verbraucht, das Geleit kehrt heim. Bericht „Außenposten … gegründet“, Erfolg „Kolonist“.
|
||||
- **Schutz:** Der Anfängerschutz erbt den Beginn des Heimathafens (keine Verlängerung); dazu **Gründungsschutz** für
|
||||
`colonyShieldHours` (24 h). Die Nachtschild-Einstellung wird übernommen. Der erste Kartell-Überfall kommt frühestens
|
||||
nach `firstRaidAfterHours` (48 h).
|
||||
|
||||
## Verlegung (Missionsart „verlegung“) und Transport
|
||||
|
||||
- Einheiten (mit Ladung und einem Admiral) fahren **dauerhaft** in einen anderen eigenen Hafen: nur Hinfahrt,
|
||||
Treibstoff einfach. Flugzeuge brauchen freie Stellplätze im Ziel (`no_aircraft_slots`).
|
||||
- Bei Ankunft wechseln die Einheiten den Hafen; ihre Erfahrung wird mit dem Bestand des Ziels gewichtet gemischt. Ein
|
||||
mitfahrender Admiral gehört danach zum Zielhafen. Rückruf auf der Hinfahrt wie bei jeder Mission.
|
||||
- **Transport** in einen eigenen Hafen ist erlaubt (wie an fremde Häfen, als Konvoi; nicht in den Ausgangshafen).
|
||||
|
||||
## Fehlercodes
|
||||
|
||||
`expansion_off`, `command_level` (Kommandozentrale des Heimathafens zu niedrig), `base_limit`, `colony_ship`,
|
||||
`not_coast`, `field_taken`, `trade_port`, `resource_field`, `too_close_own`, `too_close`, `too_far`,
|
||||
`transfer_needs_own_base`, `same_base`, `no_aircraft_slots`, `admiral_elsewhere`, `home_only`, `harbor_level`.
|
||||
@@ -487,3 +487,8 @@ Spielern (Treuhand, Gebühr, Börsenwert, Handelsstatistik) stehen in `docs/REGE
|
||||
Wahl kann keine neue Forschung beginnen. Dieselbe Wahl erneut ändert nichts; eine andere wird abgelehnt.
|
||||
Durchbrüche kosten nichts und setzen nichts ein. Bei Durchbruch gibt es eine Systemnachricht und eine Benachrichtigung.
|
||||
- Forschung gilt **je Saison**: Mit dem Stützpunkt wird sie zum Saisonende gelöscht.
|
||||
|
||||
## Mehrere Häfen
|
||||
|
||||
Gründung von Außenposten per Kolonieschiff, Verlegung zwischen eigenen Häfen und Transport in eigene Häfen stehen in
|
||||
`docs/REGELN-EXPANSION.md` (Teil dieser Regeln).
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "v1.10",
|
||||
"version": "v1.11",
|
||||
"resources": ["stahl", "treibstoff", "elektronik", "proviant"],
|
||||
"start": { "stahl": 2000, "treibstoff": 1000, "elektronik": 500, "proviant": 1000 },
|
||||
"baseTricklePerHour": { "stahl": 20, "treibstoff": 10, "elektronik": 5, "proviant": 15 },
|
||||
@@ -36,6 +36,7 @@
|
||||
"korvette": { "branch": "see", "builtIn": "werft", "cost": { "stahl": 400, "treibstoff": 100, "elektronik": 50, "proviant": 0 }, "seconds": 300, "upkeepPerHour": 2, "commandPoints": 3, "hp": 200, "attack": { "see": 40, "luft": 5, "land": 0, "anlage": 15, "uboot": 40 }, "speedKmh": 60, "fuelPer100Km": 4, "cargo": 0, "troopSpace": 0, "bonus": { "schnellboot": 1.5 } },
|
||||
"zerstoerer": { "branch": "see", "builtIn": "werft", "cost": { "stahl": 900, "treibstoff": 250, "elektronik": 200, "proviant": 0 }, "seconds": 720, "upkeepPerHour": 4, "commandPoints": 6, "hp": 450, "attack": { "see": 70, "luft": 60, "land": 0, "anlage": 30, "uboot": 60 }, "speedKmh": 55, "fuelPer100Km": 9, "cargo": 0, "troopSpace": 0, "bonus": { "korvette": 1.3 } },
|
||||
"landungsschiff": { "branch": "see", "builtIn": "werft", "cost": { "stahl": 600, "treibstoff": 200, "elektronik": 50, "proviant": 0 }, "seconds": 600, "upkeepPerHour": 3, "commandPoints": 5, "hp": 300, "attack": { "see": 5, "luft": 2, "land": 0, "anlage": 0 }, "speedKmh": 40, "fuelPer100Km": 12, "cargo": 4000, "troopSpace": 100, "bonus": {} },
|
||||
"kolonieschiff": { "branch": "see", "builtIn": "werft", "requiresLevel": 6, "cost": { "stahl": 6000, "treibstoff": 3000, "elektronik": 2000, "proviant": 2000 }, "seconds": 10800, "upkeepPerHour": 6, "commandPoints": 10, "hp": 600, "attack": { "see": 0, "luft": 0, "land": 0, "anlage": 0 }, "speedKmh": 30, "fuelPer100Km": 20, "cargo": 3000, "troopSpace": 0, "maxPerLevel": 0.2, "bonus": {} },
|
||||
"uboot": { "branch": "see", "builtIn": "werft", "requiresLevel": 3, "submerged": true, "cost": { "stahl": 700, "treibstoff": 250, "elektronik": 250, "proviant": 0 }, "seconds": 900, "upkeepPerHour": 3, "commandPoints": 6, "hp": 250, "attack": { "see": 80, "luft": 0, "land": 0, "anlage": 0, "uboot": 0 }, "speedKmh": 45, "fuelPer100Km": 6, "cargo": 0, "troopSpace": 0, "bonus": { "landungsschiff": 1.5, "schnellboot": 0.5 } },
|
||||
"minenleger": { "branch": "see", "builtIn": "werft", "requiresLevel": 4, "cost": { "stahl": 800, "treibstoff": 300, "elektronik": 250, "proviant": 0 }, "seconds": 900, "upkeepPerHour": 3, "commandPoints": 5, "hp": 300, "attack": { "see": 10, "luft": 5, "land": 0, "anlage": 0, "uboot": 0 }, "speedKmh": 40, "fuelPer100Km": 8, "cargo": 0, "troopSpace": 0, "bonus": {}, "mineLayer": 25 },
|
||||
"minenraeumer": { "branch": "see", "builtIn": "werft", "requiresLevel": 2, "cost": { "stahl": 500, "treibstoff": 150, "elektronik": 150, "proviant": 0 }, "seconds": 480, "upkeepPerHour": 2, "commandPoints": 3, "hp": 220, "attack": { "see": 15, "luft": 5, "land": 0, "anlage": 0, "uboot": 20 }, "speedKmh": 50, "fuelPer100Km": 5, "cargo": 0, "troopSpace": 0, "bonus": {}, "mineSweeper": 30 },
|
||||
@@ -330,7 +331,8 @@
|
||||
"pflichttreu": { "title": "Pflichttreu", "description": "Längste Serie: Tage in Folge alle drei Tagesbefehle abgeholt", "counter": "serie", "thresholds": [3, 7, 21] },
|
||||
"ruhmreich": { "title": "Ruhmreich", "description": "Beste Platzierung am Ende einer Saison", "counter": "saison", "thresholds": [1, 2, 3], "tierTexts": ["Platz 1 bis 10", "Platz 1 bis 3", "Saisonsieg"] },
|
||||
"wochenwerk": { "title": "Wochenwerk", "description": "Wochenziele erfüllt", "counter": "wochenziele", "thresholds": [3, 15, 50] },
|
||||
"landnahme": { "title": "Landnahme", "description": "Rohstofffelder eingenommen", "counter": "felder", "thresholds": [1, 5, 20] }
|
||||
"landnahme": { "title": "Landnahme", "description": "Rohstofffelder eingenommen", "counter": "felder", "thresholds": [1, 5, 20] },
|
||||
"kolonist": { "title": "Kolonist", "description": "Außenposten gegründet", "counter": "kolonien", "thresholds": [1, 3, 6] }
|
||||
},
|
||||
"weekly": { "goalValue": 5000, "goalCredits": 150, "bonusValue": 9000, "bonusCredits": 400, "stageGrowth": 0.3 }
|
||||
},
|
||||
@@ -368,5 +370,18 @@
|
||||
"zoneMinFields": 3,
|
||||
"zoneBonus": 0.1,
|
||||
"alliancePointsPerFieldDay": 20
|
||||
},
|
||||
"expansion": {
|
||||
"maxBases": 3,
|
||||
"unlockCommandLevels": [8, 14],
|
||||
"colonyShip": "kolonieschiff",
|
||||
"minDistanceHex": 4,
|
||||
"minDistanceOwnHex": 3,
|
||||
"maxRangeKm": 900,
|
||||
"colonyShieldHours": 24,
|
||||
"firstRaidAfterHours": 48,
|
||||
"startResources": { "stahl": 1000, "treibstoff": 500, "elektronik": 250, "proviant": 500 },
|
||||
"homeOnlyBuildings": ["forschungsamt"],
|
||||
"harborLevelForShip": 6
|
||||
}
|
||||
}
|
||||
@@ -137,7 +137,7 @@ async function blockedFor(db: DbOrTx, playerId: number, type: string, col: numbe
|
||||
.from(tables.base)
|
||||
.where(and(eq(tables.base.col, col), eq(tables.base.row, row)));
|
||||
if (!b) return null;
|
||||
if (b.playerId === playerId) return "own_base";
|
||||
if (b.playerId === playerId) return type === "transport" ? null : "own_base"; // Transport in eigenen Hafen erlaubt
|
||||
if (type === "ueberfall") return diplomacyBlock(db, playerId, b.playerId, Date.now());
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -262,7 +262,7 @@ export function launchMission(
|
||||
if (isNavalInput(input)) return launchNaval(ctx.tx, playerId, b, input, ctx.nowMs, ctx.notify);
|
||||
const target = await targetAt(ctx.tx, input.col, input.row);
|
||||
if (!target) fail("no_target");
|
||||
if (target.kind === "base" && target.playerId === playerId) fail("own_base");
|
||||
if (target.kind === "base" && target.playerId === playerId && (input.type !== "transport" || target.id === b.id)) fail("own_base"); // Transport in eigenen Hafen erlaubt
|
||||
// Allianzen/Diplomatie: kein Überfall auf Verbündete (ally) oder Paktpartner (pact).
|
||||
if (input.type === "ueberfall" && target.kind === "base" && target.playerId !== null) { const d = await diplomacyBlock(ctx.tx, playerId, target.playerId, ctx.nowMs); if (d) fail(d); }
|
||||
if (input.type === "transport" && target.kind !== "base") fail("transport_needs_base");
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
// Mehrere Häfen: Ankunft einer Gründung (neuer Hafen, Kolonieschiff verbraucht, Geleit kehrt heim) oder Verlegung
|
||||
// (Einheiten, Ladung und Admiral wechseln dauerhaft den Hafen). Regeln: docs/REGELN-EXPANSION.md.
|
||||
import { eq } from "drizzle-orm";
|
||||
import { createColony, deliverCargo, expansionOf, mergeVeterancy, returnMission, settle, type Counts, type Mission } from "@tidefront/game-core";
|
||||
import { hexCenter } from "@tidefront/world";
|
||||
import { tables, type Tx } from "@tidefront/db";
|
||||
import { balance, type NoticeJob } from "./context.ts";
|
||||
import type { HandlerResult } from "./events.ts";
|
||||
import { homeBaseOf, lockBase, lockBases, saveBase, scheduleEvent } from "./store.ts";
|
||||
import { modsOf } from "./modifiers.ts";
|
||||
import { recordAchievement } from "./achievements.ts";
|
||||
import { activeCounts, playerName, pushNotice, sendHome, storeNavalReport, type MissionRowLike, type Notes } from "./naval-common.ts";
|
||||
import { FOUNDING_TYPE, foundingCheck } from "./expansion.ts";
|
||||
|
||||
const HOUR_MS = 3600000;
|
||||
const ROMAN = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"];
|
||||
|
||||
/** Gründe einer gescheiterten Gründung als Text für den Bericht. */
|
||||
const FOUNDING_FAIL_TEXT: Record<string, string> = {
|
||||
field_taken: "Feld besetzt", too_close: "zu nah an einem fremden Hafen", too_close_own: "zu nah an einem eigenen Hafen",
|
||||
resource_field: "Rohstofffeld", trade_port: "Handelshafen", not_coast: "keine Küste", too_far: "zu weit vom Heimathafen",
|
||||
command_level: "Kommandozentrale zu niedrig", base_limit: "Höchstzahl Häfen erreicht", colony_ship: "kein Kolonieschiff",
|
||||
expansion_off: "Gründungen abgeschaltet", no_base: "kein Heimathafen",
|
||||
};
|
||||
|
||||
/** Name des neuen Hafens: „<Spielername> II“, „… III“ nach Zahl der eigenen Häfen. */
|
||||
async function colonyName(tx: Tx, playerId: number): Promise<string> {
|
||||
const n = (await tx.select({ id: tables.base.id }).from(tables.base).where(eq(tables.base.playerId, playerId))).length + 1;
|
||||
return `${await playerName(tx, playerId)} ${ROMAN[n] ?? n}`;
|
||||
}
|
||||
|
||||
/** Ankunft einer Gründung/Verlegung (mission_arrive, Weiche in handlers.ts). */
|
||||
export async function expansionArrive(tx: Tx, m: MissionRowLike & { plan: unknown }, dueMs: number): Promise<HandlerResult> {
|
||||
const plan = m.plan as Mission;
|
||||
return m.type === FOUNDING_TYPE ? foundingArrive(tx, m, plan, dueMs) : transferArrive(tx, m, plan, dueMs);
|
||||
}
|
||||
|
||||
async function foundingArrive(tx: Tx, m: MissionRowLike, plan: Mission, due: number): Promise<HandlerResult> {
|
||||
const pid = m.playerId!;
|
||||
const notify: Notes = [[[pid], "missions"], [[pid], "reports"], [[pid], "base"]];
|
||||
const push: NoticeJob[] = [];
|
||||
const e = expansionOf(balance);
|
||||
const origin = await lockBase(tx, m.baseId!); // Sperre vor dem Anlegen des neuen Hafens
|
||||
const at = { col: m.targetCol, row: m.targetRow };
|
||||
let blocker = e ? await foundingCheck(tx, pid, at, undefined, m.id) : "expansion_off";
|
||||
if (!blocker && (plan.units[e!.colonyShip] ?? 0) < 1) blocker = "colony_ship";
|
||||
let baseId: number | null = null;
|
||||
let name = "";
|
||||
if (!blocker) {
|
||||
const home = (await homeBaseOf(tx, pid))!;
|
||||
name = await colonyName(tx, pid);
|
||||
const state = createColony(balance, due, hexCenter(at.col, at.row), home.state.protection, plan.cargo);
|
||||
// Wettlauf: base_field ist eindeutig; der Verlierer bekommt „Feld besetzt“.
|
||||
const ins = await tx.insert(tables.base).values({ playerId: pid, name, col: at.col, row: at.row, state, isHome: false })
|
||||
.onConflictDoNothing().returning({ id: tables.base.id });
|
||||
if (ins.length === 0) blocker = "field_taken";
|
||||
else baseId = ins[0].id;
|
||||
}
|
||||
if (blocker || baseId === null) {
|
||||
const reason = FOUNDING_FAIL_TEXT[blocker!] ?? blocker!;
|
||||
const title = `Gründung gescheitert: ${reason}`;
|
||||
const reportId = await storeNavalReport(tx, {
|
||||
kind: "gruendung", title, attackerPlayerId: pid, defenderPlayerId: null, attackerBaseId: m.baseId, atMs: due,
|
||||
report: { founding: { col: at.col, row: at.row, ok: false, code: blocker, units: plan.units, cargo: plan.cargo } },
|
||||
});
|
||||
await sendHome(tx, m, plan, activeCounts(plan.units), plan.cargo ?? {}, reportId, due);
|
||||
push.push(pushNotice(pid, "report", title, "Das Kolonieschiff kehrt mit seiner Ladung heim.", "berichte"));
|
||||
return { notify, push };
|
||||
}
|
||||
await scheduleEvent(tx, "raid_launch", due + (e!.firstRaidAfterHours * HOUR_MS), {}, baseId);
|
||||
const escort: Counts = {};
|
||||
for (const [id, n] of Object.entries(activeCounts(plan.units))) {
|
||||
const k = id === e!.colonyShip ? n - 1 : n;
|
||||
if (k > 0) escort[id] = k;
|
||||
}
|
||||
const title = `Außenposten ${name} gegründet`;
|
||||
const reportId = await storeNavalReport(tx, {
|
||||
kind: "gruendung", title, attackerPlayerId: pid, defenderPlayerId: null, attackerBaseId: m.baseId, defenderBaseId: baseId, atMs: due,
|
||||
report: { founding: { col: at.col, row: at.row, ok: true, baseId, name, cargo: plan.cargo, escort } },
|
||||
});
|
||||
if (Object.keys(escort).length > 0) {
|
||||
await sendHome(tx, m, plan, escort, {}, reportId, due); // Geleit kehrt heim; das Kolonieschiff fehlt bei der Rückkehr
|
||||
} else {
|
||||
if (origin) await saveBase(tx, origin.id, returnMission(origin.state, plan.units, {}, {}, due, balance, await modsOf(tx, origin, due)));
|
||||
await tx.update(tables.mission).set({ status: "done", returning: {}, cargoHome: {}, reportId, returnAt: new Date(due) }).where(eq(tables.mission.id, m.id));
|
||||
}
|
||||
await recordAchievement(tx, pid, "kolonien", 1, { atMs: due }); // Erfolg „Kolonist“
|
||||
push.push(pushNotice(pid, "report", title, "Dein neuer Hafen steht unter Gründungsschutz.", "berichte"));
|
||||
notify.push([null, "map"]);
|
||||
return { notify, push };
|
||||
}
|
||||
|
||||
async function transferArrive(tx: Tx, m: MissionRowLike, plan: Mission, due: number): Promise<HandlerResult> {
|
||||
const pid = m.playerId!;
|
||||
const notify: Notes = [[[pid], "missions"], [[pid], "reports"], [[pid], "base"]];
|
||||
const bases = await lockBases(tx, [m.baseId!, m.targetId ?? m.baseId!]); // aufsteigend
|
||||
const origin = bases.get(m.baseId!);
|
||||
const target = m.targetId !== null ? bases.get(m.targetId) : undefined;
|
||||
const units = activeCounts(plan.units);
|
||||
if (!origin || !target || target.playerId !== pid || target.id === origin.id) {
|
||||
const reportId = await storeNavalReport(tx, {
|
||||
kind: "verlegung", title: "Verlegung abgebrochen: Zielhafen fehlt", attackerPlayerId: pid, defenderPlayerId: null, attackerBaseId: m.baseId, atMs: due,
|
||||
report: { transfer: { ok: false, units, cargo: plan.cargo } },
|
||||
});
|
||||
const returnAt = due + Math.max(0, plan.arriveAtMs - plan.departAtMs);
|
||||
await tx.update(tables.mission).set({ status: "returning", returning: units, cargoHome: plan.cargo ?? {}, reportId, returnAt: new Date(returnAt) }).where(eq(tables.mission.id, m.id));
|
||||
await scheduleEvent(tx, "mission_return", returnAt, { missionId: m.id }, m.baseId);
|
||||
return { notify };
|
||||
}
|
||||
const from = returnMission(origin.state, plan.units, {}, {}, due, balance, await modsOf(tx, origin, due));
|
||||
const to = deliverCargo(settle(target.state, due, balance, await modsOf(tx, target, due)), plan.cargo ?? {}, due, balance, await modsOf(tx, target, due));
|
||||
// Veteranen: Erfahrung des Ausgangshafens, gewichtet mit dem Bestand des Ziels gemischt.
|
||||
const vet = mergeVeterancy(to, origin.state.veterancy, units);
|
||||
if (vet) to.veterancy = vet;
|
||||
else delete to.veterancy;
|
||||
for (const [id, n] of Object.entries(units)) to.units[id] = (to.units[id] ?? 0) + n;
|
||||
await saveBase(tx, origin.id, from);
|
||||
await saveBase(tx, target.id, to);
|
||||
if (plan.admiralId !== undefined) {
|
||||
await tx.update(tables.admiral).set({ baseId: target.id }).where(eq(tables.admiral.id, plan.admiralId)); // mitfahrender Admiral wechselt den Hafen
|
||||
}
|
||||
const reportId = await storeNavalReport(tx, {
|
||||
kind: "verlegung", title: `Verlegung nach ${target.name} angekommen`, attackerPlayerId: pid, defenderPlayerId: null,
|
||||
attackerBaseId: origin.id, defenderBaseId: target.id, atMs: due,
|
||||
report: { transfer: { ok: true, from: origin.name, to: target.name, units, cargo: plan.cargo, admiralId: plan.admiralId ?? null } },
|
||||
});
|
||||
await tx.update(tables.mission).set({ status: "done", returning: units, cargoHome: {}, reportId, returnAt: new Date(due) }).where(eq(tables.mission.id, m.id));
|
||||
return { notify };
|
||||
}
|
||||
@@ -1,19 +1,30 @@
|
||||
// Mehrere Häfen je Spieler: Gründung eines Außenpostens und Verlegung zwischen eigenen Häfen.
|
||||
// P0 (Fundament): nur Stub – die Missionsarten sind bekannt, aber noch abgeschaltet ("expansion_off").
|
||||
// P1 ersetzt launchExpansion, previewExpansion und expansionArrive.
|
||||
import type { Counts, ResourceMap } from "@tidefront/game-core";
|
||||
import type { DbOrTx, Tx } from "@tidefront/db";
|
||||
import { hexDistanceKm } from "@tidefront/world";
|
||||
import { GameError } from "./context.ts";
|
||||
import type { HandlerResult } from "./events.ts";
|
||||
import type { MissionRowLike, Notes } from "./naval-common.ts";
|
||||
import type { BaseRow } from "./store.ts";
|
||||
import type { missionWeather } from "./weather.ts";
|
||||
// Mehrere Häfen je Spieler: Gründung eines Außenpostens (Kolonieschiff auf ein freies Küstenfeld) und Verlegung von
|
||||
// Einheiten zwischen eigenen Häfen (docs/REGELN-EXPANSION.md). Hier: Prüfungen, Planung, Auslaufen und Vorschau;
|
||||
// die Ankunft steht in expansion-arrive.ts. Eingehängt in commands.ts (launchMission), views.ts (missionPreview)
|
||||
// und handlers.ts (missionArrive).
|
||||
import { and, eq, ne } from "drizzle-orm";
|
||||
import {
|
||||
aircraftSlots, aircraftSlotsUsed, allowedBases, combineModifiers, expansionOf, foundingBlocker, planMission,
|
||||
type Counts, type Modifiers, type ResourceMap,
|
||||
} from "@tidefront/game-core";
|
||||
import { TRADE_PORTS, hexAtLonLat, hexCenter, hexDistanceKm, isCoast } from "@tidefront/world";
|
||||
import { tables, type DbOrTx, type Tx } from "@tidefront/db";
|
||||
import { balance, GameError } from "./context.ts";
|
||||
import { activeMissionCount, homeBaseOf, scheduleEvent, type BaseRow } from "./store.ts";
|
||||
import { modsOf } from "./modifiers.ts";
|
||||
import { missionWeather, withArrival } from "./weather.ts";
|
||||
import { admiralForLaunch, admiralPreviewMods, assignAdmiral } from "./admirals-core.ts";
|
||||
import type { Notes } from "./naval-common.ts";
|
||||
|
||||
/** Missionsart: Kolonieschiff gründet auf einem freien Küstenfeld einen neuen Hafen. */
|
||||
export const FOUNDING_TYPE = "gruendung";
|
||||
/** Missionsart: Einheiten (und Admiral) dauerhaft in einen anderen eigenen Hafen verlegen. */
|
||||
export const TRANSFER_TYPE = "verlegung";
|
||||
/** Zielarten der Missionszeilen (nicht „base“, damit die Verlegung nicht als Anmarsch auf den Zielhafen zählt). */
|
||||
export const SITE_TARGET = "site";
|
||||
export const OWN_BASE_TARGET = "own_base";
|
||||
|
||||
export { expansionArrive } from "./expansion-arrive.ts";
|
||||
|
||||
/** Eingabe einer Gründung/Verlegung (Teilmenge von LaunchInput). */
|
||||
export interface ExpansionInput {
|
||||
@@ -33,33 +44,126 @@ function fail(code: string): never {
|
||||
throw new GameError(code);
|
||||
}
|
||||
|
||||
/** Auslaufen einer Gründung/Verlegung aus dem gesperrten Hafen `own` (in runCommand). */
|
||||
export async function launchExpansion(
|
||||
_tx: Tx,
|
||||
_playerId: number,
|
||||
_own: BaseRow,
|
||||
_input: ExpansionInput,
|
||||
_nowMs: number,
|
||||
_notify: Notes,
|
||||
): Promise<{ ok: true; missionId: number; arriveAtMs: number }> {
|
||||
return fail("expansion_off");
|
||||
const TRADE_HEXES = TRADE_PORTS.map(([lon, lat]) => hexAtLonLat(lon, lat));
|
||||
|
||||
/** Laufende Gründungen des Spielers (ohne `exceptMissionId`). */
|
||||
async function pendingFoundings(db: DbOrTx, playerId: number, exceptMissionId?: number): Promise<number> {
|
||||
const rows = await db.select({ id: tables.mission.id }).from(tables.mission).where(and(
|
||||
eq(tables.mission.playerId, playerId), eq(tables.mission.type, FOUNDING_TYPE), eq(tables.mission.status, "outbound"),
|
||||
...(exceptMissionId !== undefined ? [ne(tables.mission.id, exceptMissionId)] : []),
|
||||
));
|
||||
return rows.length;
|
||||
}
|
||||
|
||||
/** Antwort der Vorschau (Form wie missionPreview; P1 ergänzt den ok-true-Fall). */
|
||||
export type ExpansionPreview = { ok: false; code: string; distanceKm: number; weather?: ReturnType<typeof missionWeather> };
|
||||
/**
|
||||
* Grund gegen eine Gründung auf (col,row) oder null. Liest Häfen, Nester und Rohstofffelder (resource_field);
|
||||
* `units` fehlt bei der Ankunft (Kolonieschiff dann vom Aufrufer geprüft). Codes siehe game-core foundingBlocker, dazu no_base.
|
||||
*/
|
||||
export async function foundingCheck(db: DbOrTx, playerId: number, target: { col: number; row: number }, units?: Counts, exceptMissionId?: number): Promise<string | null> {
|
||||
const home = await homeBaseOf(db, playerId);
|
||||
if (!home) return "no_base";
|
||||
const bases = await db.select({ playerId: tables.base.playerId, col: tables.base.col, row: tables.base.row }).from(tables.base);
|
||||
const nests = await db.select({ col: tables.nest.col, row: tables.nest.row }).from(tables.nest);
|
||||
const fields = await db.select({ col: tables.resourceField.col, row: tables.resourceField.row }).from(tables.resourceField);
|
||||
return foundingBlocker({
|
||||
target: { col: target.col, row: target.row },
|
||||
coast: isCoast(target.col, target.row),
|
||||
homeDistanceKm: hexDistanceKm(home, target),
|
||||
bases: bases.map((b) => ({ col: b.col, row: b.row, own: b.playerId === playerId })),
|
||||
nests, tradePorts: TRADE_HEXES, fields,
|
||||
homeState: home.state,
|
||||
ownBases: bases.filter((b) => b.playerId === playerId).length,
|
||||
pendingFoundings: await pendingFoundings(db, playerId, exceptMissionId),
|
||||
units,
|
||||
}, balance);
|
||||
}
|
||||
|
||||
/** Vorschau einer Gründung/Verlegung. */
|
||||
export async function previewExpansion(
|
||||
_db: DbOrTx,
|
||||
_playerId: number,
|
||||
/** Ziel einer Verlegung: anderer eigener Hafen. Codes: transfer_needs_own_base, same_base, no_aircraft_slots. */
|
||||
async function transferTarget(db: DbOrTx, playerId: number, own: BaseRow, input: ExpansionInput) {
|
||||
const [t] = await db.select().from(tables.base).where(and(eq(tables.base.col, input.col), eq(tables.base.row, input.row)));
|
||||
if (!t || t.playerId !== playerId) fail("transfer_needs_own_base");
|
||||
if (t.id === own.id) fail("same_base");
|
||||
const state = t.state as BaseRow["state"];
|
||||
const planes = Object.entries(input.units).reduce((s, [id, n]) => s + (balance.units[id]?.branch === "luft" && n > 0 ? n : 0), 0);
|
||||
if (planes > 0 && aircraftSlotsUsed(state, balance) + planes > aircraftSlots(state, balance)) fail("no_aircraft_slots");
|
||||
return t;
|
||||
}
|
||||
|
||||
/** Prüfungen und Planung beider Arten; wirft GameError mit dem Ablehnungsgrund. */
|
||||
async function planExpansion(db: DbOrTx, playerId: number, own: BaseRow, input: ExpansionInput, nowMs: number, admiralMods: Modifiers | null) {
|
||||
if (!expansionOf(balance)) fail("expansion_off");
|
||||
let targetId: number | null = null;
|
||||
if (input.type === FOUNDING_TYPE) {
|
||||
const blocker = await foundingCheck(db, playerId, input, input.units);
|
||||
if (blocker) fail(blocker);
|
||||
} else {
|
||||
targetId = (await transferTarget(db, playerId, own, input)).id;
|
||||
}
|
||||
const weather = missionWeather(own.col, own.row, input.col, input.row, nowMs);
|
||||
const r = planMission(own.state, {
|
||||
type: input.type, units: input.units, origin: hexCenter(own.col, own.row), target: hexCenter(input.col, input.row),
|
||||
activeMissions: await activeMissionCount(db, own.id), cargo: input.cargo, weather,
|
||||
}, nowMs, balance, combineModifiers(await modsOf(db, own, nowMs), admiralMods ?? undefined));
|
||||
return { r, targetId, weather };
|
||||
}
|
||||
|
||||
/** Auslaufen einer Gründung/Verlegung aus dem gesperrten Hafen `own` (in runCommand). Codes zusätzlich: admiral_elsewhere. */
|
||||
export async function launchExpansion(
|
||||
tx: Tx,
|
||||
playerId: number,
|
||||
own: BaseRow,
|
||||
input: ExpansionInput,
|
||||
_nowMs: number,
|
||||
): Promise<ExpansionPreview> {
|
||||
return { ok: false as const, code: "expansion_off", distanceKm: hexDistanceKm(own, input) };
|
||||
nowMs: number,
|
||||
notify: Notes,
|
||||
): Promise<{ ok: true; missionId: number; arriveAtMs: number } | { ok: false; code: string }> {
|
||||
const adm = input.admiralId !== undefined ? await admiralForLaunch(tx, playerId, input.admiralId, nowMs) : null;
|
||||
if (adm) {
|
||||
const [a] = await tx.select({ baseId: tables.admiral.baseId }).from(tables.admiral).where(eq(tables.admiral.id, adm.id));
|
||||
if (a.baseId !== own.id) fail("admiral_elsewhere");
|
||||
}
|
||||
const { r, targetId } = await planExpansion(tx, playerId, own, input, nowMs, adm?.mods ?? null);
|
||||
if (!r.ok) return r;
|
||||
await tx.update(tables.base).set({ state: r.base }).where(eq(tables.base.id, own.id));
|
||||
const plan = adm ? { ...r.mission, admiralId: adm.id } : r.mission;
|
||||
const [m] = await tx.insert(tables.mission).values({
|
||||
playerId, baseId: own.id, type: input.type, targetKind: targetId === null ? SITE_TARGET : OWN_BASE_TARGET, targetId,
|
||||
targetCol: input.col, targetRow: input.row, plan, status: "outbound", arriveAt: new Date(r.mission.arriveAtMs),
|
||||
}).returning({ id: tables.mission.id });
|
||||
// Verlegung: Ankunft am Zielhafen (wird vor Befehlen dieses Hafens verarbeitet); Gründung ohne Hafen.
|
||||
await scheduleEvent(tx, "mission_arrive", r.mission.arriveAtMs, { missionId: m.id }, targetId);
|
||||
if (adm) await assignAdmiral(tx, adm.id, m.id);
|
||||
notify.push([[playerId], "base"], [[playerId], "missions"]);
|
||||
return { ok: true as const, missionId: m.id, arriveAtMs: r.mission.arriveAtMs };
|
||||
}
|
||||
|
||||
/** Ankunft einer Gründung/Verlegung (mission_arrive, Weiche in handlers.ts). */
|
||||
export async function expansionArrive(_tx: Tx, _m: MissionRowLike, _dueMs: number): Promise<HandlerResult> {
|
||||
return fail("expansion_off");
|
||||
/** Antwort der Vorschau (Form wie missionPreview). */
|
||||
export type ExpansionPreview =
|
||||
| { ok: false; code: string; distanceKm: number; weather?: ReturnType<typeof missionWeather> }
|
||||
| {
|
||||
ok: true; distanceKm: number; travelSeconds: number; fuelCost: number; arriveAtMs: number; returnAtMs: number;
|
||||
target: { kind: string; own: boolean }; intercept: null; weather: ReturnType<typeof missionWeather>; weatherFactor: number;
|
||||
/** Häfen: eigene, laufende Gründungen, erlaubt (Kommandozentrale des Heimathafens), Höchstzahl. */
|
||||
expansion: { bases: number; pending: number; allowed: number; max: number };
|
||||
};
|
||||
|
||||
/** Vorschau einer Gründung/Verlegung mit Ablehnungsgrund (Code) wie launchExpansion. */
|
||||
export async function previewExpansion(db: DbOrTx, playerId: number, own: BaseRow, input: ExpansionInput, nowMs: number): Promise<ExpansionPreview> {
|
||||
const distanceKm = hexDistanceKm(own, input);
|
||||
try {
|
||||
const { r, weather } = await planExpansion(db, playerId, own, input, nowMs, await admiralPreviewMods(db, playerId, input.admiralId));
|
||||
if (!r.ok) return { ok: false as const, code: r.code, distanceKm, weather };
|
||||
const home = await homeBaseOf(db, playerId);
|
||||
const e = expansionOf(balance)!;
|
||||
const bases = await db.select({ id: tables.base.id }).from(tables.base).where(eq(tables.base.playerId, playerId));
|
||||
const m = r.mission;
|
||||
return {
|
||||
ok: true as const, distanceKm: m.distanceKm, travelSeconds: m.travelSeconds, fuelCost: m.fuelCost, arriveAtMs: m.arriveAtMs,
|
||||
returnAtMs: m.returnAtMs, target: { kind: input.type === FOUNDING_TYPE ? SITE_TARGET : "base", own: input.type === TRANSFER_TYPE },
|
||||
intercept: null, weather: withArrival(weather, input.col, input.row, m.arriveAtMs), weatherFactor: m.weather?.shipFactor ?? 1,
|
||||
expansion: { bases: bases.length, pending: await pendingFoundings(db, playerId), allowed: home ? allowedBases(home.state, balance) : 1, max: e.maxBases },
|
||||
};
|
||||
} catch (err) {
|
||||
if (err instanceof GameError) return { ok: false as const, code: err.code, distanceKm };
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -289,7 +289,7 @@ export async function missionPreview(
|
||||
const distanceKm = hexDistanceKm(own, input);
|
||||
if (!target) return { ok: false as const, code: "no_target", distanceKm };
|
||||
// Dieselben Ablehnungen wie launchMission, schon in der Vorschau (Planung zeigt den Grund).
|
||||
if (target.kind === "base" && target.playerId === playerId) return { ok: false as const, code: "own_base", distanceKm };
|
||||
if (target.kind === "base" && target.playerId === playerId && (input.type !== "transport" || target.id === own.id)) return { ok: false as const, code: "own_base", distanceKm }; // Transport in eigenen Hafen erlaubt
|
||||
if (input.type === "ueberfall" && target.kind === "base" && target.playerId !== null) {
|
||||
const d = await diplomacyBlock(engine.db, playerId, target.playerId, nowMs);
|
||||
if (d) return { ok: false as const, code: d, distanceKm };
|
||||
|
||||
@@ -178,12 +178,12 @@ test("Befehl mit baseId der Kolonie wirkt auf die Kolonie; base.get liefert Hafe
|
||||
assert.equal(view.base?.isHome, false);
|
||||
assert.equal(view.base?.buildQueue.length, 1);
|
||||
|
||||
// Gründung/Verlegung sind in P0 noch abgeschaltet.
|
||||
for (const type of [FOUNDING_TYPE, TRANSFER_TYPE]) {
|
||||
assert.deepEqual(await launchMission(engine, p.playerId, key(), { type, units: {}, col: 3, row: 3 }), { ok: false, code: "expansion_off" });
|
||||
// Gründung/Verlegung laufen über die Weiche (P1, expansion.ts); ohne Kolonieschiff bzw. Zielhafen abgelehnt.
|
||||
for (const [type, expected] of [[FOUNDING_TYPE, "command_level"], [TRANSFER_TYPE, "transfer_needs_own_base"]] as const) {
|
||||
assert.deepEqual(await launchMission(engine, p.playerId, key(), { type, units: {}, col: 3, row: 3 }), { ok: false, code: expected });
|
||||
const pv = await missionPreview(engine, p.playerId, { type, units: {}, col: 3, row: 3 });
|
||||
assert.equal(pv.ok, false);
|
||||
assert.equal((pv as { code: string }).code, "expansion_off");
|
||||
assert.equal((pv as { code: string }).code, expected);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
// Integrationstests Mehrere Häfen P1 (TEST_DATABASE_URL; die Datenbank wird geleert): Gründung mit Geleit und Ladung,
|
||||
// Obergrenze inkl. laufender Gründungen, Mindestabstand, Reichweite, Wettlauf um ein Feld, Schutz der Kolonie,
|
||||
// Forschungsamt gesperrt, Verlegung mit Veteranen und Admiral, Transport in eigenen Hafen, Saisonende.
|
||||
import { after, before, test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { createDb, migrateDb, tables } from "@tidefront/db";
|
||||
import { COLS, ROWS, TRADE_PORTS, hexAtLonLat, hexDistanceKm, isCoast, nestSites } from "@tidefront/world";
|
||||
import { hexSteps, type BaseState } from "@tidefront/game-core";
|
||||
import {
|
||||
admiralSpecIds, balance, basesOfPlayer, chooseBase, homeBaseOf, launchMission, missionPreview, processDue, register,
|
||||
runningSeason, seasonEnd, seed, upgrade, type Engine,
|
||||
} from "../src/index.ts";
|
||||
|
||||
const url = process.env.TEST_DATABASE_URL;
|
||||
const HOUR = 3600000;
|
||||
const DAY = 24 * HOUR;
|
||||
const { db, client } = createDb(url ?? "postgres://invalid", 20);
|
||||
const engine: Engine = { db, notify: () => {}, log: () => {} };
|
||||
let keyN = 0;
|
||||
const key = () => `ex${++keyN}-${Date.now()}`;
|
||||
const E = balance.expansion!;
|
||||
const SHIP = E.colonyShip;
|
||||
const nests = new Set(nestSites().map((n) => `${n.col},${n.row}`));
|
||||
const ports = new Set(TRADE_PORTS.map(([lon, lat]) => { const h = hexAtLonLat(lon, lat); return `${h.col},${h.row}`; }));
|
||||
type Hex = { col: number; row: number };
|
||||
|
||||
/** Küstenfeld, das die Regeln erfüllt: Abstand zu allen Häfen ≥ minSteps, Entfernung zu `near` in [minKm, maxKm]. */
|
||||
async function freeCoast(near: Hex | null, minKm: number, maxKm: number, minSteps = E.minDistanceHex + 1, avoid: Hex[] = []): Promise<Hex> {
|
||||
const bases = await db.select({ col: tables.base.col, row: tables.base.row }).from(tables.base);
|
||||
for (let row = 20; row < ROWS; row++) for (let col = 10; col < COLS; col++) {
|
||||
const k = `${col},${row}`;
|
||||
if (!isCoast(col, row) || nests.has(k) || ports.has(k)) continue;
|
||||
const h = { col, row };
|
||||
if ([...bases, ...avoid].some((b) => hexSteps(b, h) < minSteps)) continue;
|
||||
if (near) { const d = hexDistanceKm(near, h); if (d < minKm || d > maxKm) continue; }
|
||||
return h;
|
||||
}
|
||||
throw new Error("kein Küstenfeld");
|
||||
}
|
||||
|
||||
/** Küstenfeld (kein Nest, kein Hafen) im Abstand [minSteps, maxSteps] Feldschritte um `c`. */
|
||||
function coastAround(c: Hex, minSteps: number, maxSteps: number): Hex {
|
||||
for (let r = c.row - maxSteps; r <= c.row + maxSteps; r++) for (let k = c.col - maxSteps; k <= c.col + maxSteps; k++) {
|
||||
const h = { col: k, row: r };
|
||||
const d = hexSteps(h, c);
|
||||
if (d >= minSteps && d <= maxSteps && isCoast(k, r) && !nests.has(`${k},${r}`) && !ports.has(`${k},${r}`)) return h;
|
||||
}
|
||||
throw new Error("kein Küstenfeld in der Nähe");
|
||||
}
|
||||
|
||||
async function patchBase(baseId: number, patch: (s: BaseState) => void) {
|
||||
const [b] = await db.select().from(tables.base).where(eq(tables.base.id, baseId));
|
||||
const s = b.state as BaseState;
|
||||
patch(s);
|
||||
await db.update(tables.base).set({ state: s }).where(eq(tables.base.id, baseId));
|
||||
}
|
||||
|
||||
async function stateOf(baseId: number): Promise<BaseState> {
|
||||
const [b] = await db.select().from(tables.base).where(eq(tables.base.id, baseId));
|
||||
return b.state as BaseState;
|
||||
}
|
||||
|
||||
async function newPlayer(name: string, field: Hex, kz = 8) {
|
||||
const p = await register(db, { inviteCode: "TEST", name, password: "geheim123" });
|
||||
const r = await chooseBase(engine, p.playerId, key(), { ...field, name: `Hafen ${name}`, nightShieldStartHour: 23, tzOffsetMinutes: 60 });
|
||||
assert.equal(r.ok, true, JSON.stringify(r));
|
||||
const baseId = (r as { baseId: number }).baseId;
|
||||
await patchBase(baseId, (s) => {
|
||||
s.protection.createdAtMs = Date.now() - 30 * DAY;
|
||||
s.resources = { stahl: 200_000, treibstoff: 200_000, elektronik: 200_000, proviant: 200_000 };
|
||||
Object.assign(s.buildings, { kommandozentrale: kz, hafenkommandantur: 6, werft: 6, lagerkomplex: 12, flugfeld: 2 });
|
||||
s.units = { [SHIP]: 3, korvette: 20, zerstoerer: 5 };
|
||||
});
|
||||
await db.delete(tables.gameEvent).where(sql`${tables.gameEvent.type} = 'raid_launch' or ${tables.gameEvent.type} like 'world_event%'`);
|
||||
return { playerId: p.playerId, baseId, ...field };
|
||||
}
|
||||
|
||||
async function runUntil(ms: number) {
|
||||
while ((await processDue(engine, ms, 500)) > 0);
|
||||
}
|
||||
|
||||
const code = (r: { ok: boolean; code?: string }) => (r.ok ? "ok" : r.code);
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
let A: Awaited<ReturnType<typeof newPlayer>>;
|
||||
let colonyId = 0;
|
||||
|
||||
test("Gründung: Vorschau, Ablehnungen, Obergrenze inkl. laufender Gründung, neuer Hafen, Kolonieschiff verbraucht, Geleit kehrt heim", async () => {
|
||||
A = await newPlayer("Kolonist", await freeCoast(null, 0, 0));
|
||||
const target = await freeCoast(A, 350, 600);
|
||||
const units = { [SHIP]: 1, korvette: 2 };
|
||||
const pv = await missionPreview(engine, A.playerId, { type: "gruendung", units, col: target.col, row: target.row, cargo: { stahl: 1500 } });
|
||||
assert.equal(pv.ok, true, JSON.stringify(pv));
|
||||
assert.deepEqual((pv as { expansion: unknown }).expansion, { bases: 1, pending: 0, allowed: 2, max: E.maxBases });
|
||||
// Ablehnungen in der Vorschau.
|
||||
assert.equal(code(await missionPreview(engine, A.playerId, { type: "gruendung", units: { korvette: 2 }, col: target.col, row: target.row })), "colony_ship");
|
||||
assert.equal(code(await missionPreview(engine, A.playerId, { type: "gruendung", units: { [SHIP]: 2 }, col: target.col, row: target.row })), "colony_ship");
|
||||
const far = await freeCoast(A, E.maxRangeKm + 50, E.maxRangeKm + 600);
|
||||
assert.equal(code(await missionPreview(engine, A.playerId, { type: "gruendung", units, col: far.col, row: far.row })), "too_far");
|
||||
assert.equal(code(await missionPreview(engine, A.playerId, { type: "gruendung", units, col: A.col, row: A.row })), "field_taken");
|
||||
const own = coastAround(A, 1, E.minDistanceOwnHex - 1);
|
||||
assert.equal(code(await missionPreview(engine, A.playerId, { type: "gruendung", units, ...own })), "too_close_own");
|
||||
|
||||
const go = await launchMission(engine, A.playerId, key(), { type: "gruendung", units, col: target.col, row: target.row, cargo: { stahl: 1500 } });
|
||||
assert.equal(go.ok, true, JSON.stringify(go));
|
||||
// Obergrenze: Kommandozentrale 8 erlaubt 2 Häfen – die laufende Gründung zählt mit.
|
||||
const other = await freeCoast(A, 350, 800, E.minDistanceHex + 1, [target]);
|
||||
assert.equal(code(await launchMission(engine, A.playerId, key(), { type: "gruendung", units: { [SHIP]: 1 }, col: other.col, row: other.row })), "command_level");
|
||||
let s = await stateOf(A.baseId);
|
||||
assert.equal(s.units[SHIP], 2);
|
||||
assert.equal(s.unitsAway[SHIP], 1);
|
||||
const arriveAt = (go as { arriveAtMs: number }).arriveAtMs;
|
||||
await runUntil(arriveAt + 1000);
|
||||
|
||||
const bases = await basesOfPlayer(db, A.playerId);
|
||||
assert.equal(bases.length, 2);
|
||||
const col = bases.find((b) => !b.isHome)!;
|
||||
colonyId = col.id;
|
||||
assert.deepEqual([col.col, col.row], [target.col, target.row]);
|
||||
assert.equal(col.name, "Kolonist II");
|
||||
assert.equal(col.state.resources.stahl, E.startResources.stahl + 1500);
|
||||
assert.equal(col.state.resources.elektronik, E.startResources.elektronik);
|
||||
assert.ok(col.state.colony);
|
||||
// Schutz: Anfängerschutz erbt den Beginn (vorbei), 24 h Gründungsschutz, Nachtschild übernommen.
|
||||
const home = (await homeBaseOf(db, A.playerId))!;
|
||||
assert.equal(col.state.protection.createdAtMs, home.state.protection.createdAtMs);
|
||||
assert.ok(Math.abs((col.state.protection.foundingShieldUntilMs ?? 0) - (arriveAt + E.colonyShieldHours * HOUR)) < 5000);
|
||||
assert.equal(col.state.protection.nightShieldStartHour, 23);
|
||||
assert.equal(col.state.protection.tzOffsetMinutes, 60);
|
||||
// Erster Kartell-Überfall nach firstRaidAfterHours.
|
||||
const [raid] = await db.select().from(tables.gameEvent).where(and(eq(tables.gameEvent.type, "raid_launch"), eq(tables.gameEvent.baseId, col.id)));
|
||||
assert.ok(raid && Math.abs(raid.dueAt.getTime() - (arriveAt + E.firstRaidAfterHours * HOUR)) < 5000);
|
||||
// Bericht, Erfolgszähler.
|
||||
const [rep] = await db.select().from(tables.battleReport).where(and(eq(tables.battleReport.kind, "gruendung"), eq(tables.battleReport.attackerPlayerId, A.playerId)));
|
||||
assert.match(rep.title, /gegründet/);
|
||||
const [cnt] = await db.select().from(tables.achievementCounter).where(and(eq(tables.achievementCounter.playerId, A.playerId), eq(tables.achievementCounter.counter, "kolonien")));
|
||||
assert.equal(cnt?.value, 1);
|
||||
// Geleit kehrt heim, das Kolonieschiff nicht.
|
||||
const [m] = await db.select().from(tables.mission).where(eq(tables.mission.id, (go as { missionId: number }).missionId));
|
||||
assert.equal(m.status, "returning");
|
||||
assert.deepEqual(m.returning, { korvette: 2 });
|
||||
await runUntil(m.returnAt!.getTime() + 1000);
|
||||
s = await stateOf(A.baseId);
|
||||
assert.equal(s.units[SHIP], 2, "verbraucht");
|
||||
assert.equal(s.unitsAway[SHIP] ?? 0, 0);
|
||||
assert.equal(s.units.korvette, 20);
|
||||
// Danach erlaubt Kommandozentrale 8 keinen dritten Hafen.
|
||||
assert.equal(code(await missionPreview(engine, A.playerId, { type: "gruendung", units: { [SHIP]: 1 }, col: other.col, row: other.row })), "command_level");
|
||||
// Kolonie: Zeit auf jetzt, damit spätere Befehle nicht vor dem Gründungszeitpunkt rechnen.
|
||||
await patchBase(colonyId, (st) => { st.resUpdatedAt = Date.now(); });
|
||||
});
|
||||
|
||||
test("Forschungsamt in der Kolonie gesperrt, Mindestabstand zu fremden Häfen", async () => {
|
||||
assert.equal(code(await upgrade(engine, A.playerId, key(), "forschungsamt", colonyId)), "home_only");
|
||||
assert.equal(code(await upgrade(engine, A.playerId, key(), "stahlwerk", colonyId)), "ok");
|
||||
const col = (await basesOfPlayer(db, A.playerId)).find((b) => b.id === colonyId)!;
|
||||
const B = await newPlayer("Nachbar", await freeCoast(col, 600, 900), 14);
|
||||
// Feld 1–3 Schritte neben A's Kolonie: zu nah an fremdem Hafen.
|
||||
const close = coastAround(col, 1, E.minDistanceHex - 1);
|
||||
assert.equal(code(await missionPreview(engine, B.playerId, { type: "gruendung", units: { [SHIP]: 1 }, ...close })), "too_close");
|
||||
});
|
||||
|
||||
test("Wettlauf um ein Feld: der zweite bekommt „Feld besetzt“, Kolonieschiff und Ladung kehren heim", async () => {
|
||||
const P = await newPlayer("Erster", await freeCoast(null, 0, 0), 14);
|
||||
const target = await freeCoast(P, 300, 500);
|
||||
const Q = await newPlayer("Zweiter", await freeCoast(target, 350, 700, E.minDistanceHex + 1, [target]), 14);
|
||||
const a = await launchMission(engine, P.playerId, key(), { type: "gruendung", units: { [SHIP]: 1 }, ...target, cargo: { stahl: 1000 } });
|
||||
const b = await launchMission(engine, Q.playerId, key(), { type: "gruendung", units: { [SHIP]: 1, korvette: 1 }, ...target, cargo: { stahl: 1000 } });
|
||||
assert.equal(a.ok && b.ok, true, JSON.stringify([a, b]));
|
||||
const ta = (a as { arriveAtMs: number }).arriveAtMs;
|
||||
const tb = (b as { arriveAtMs: number }).arriveAtMs;
|
||||
const [winner, loser, loserMission] = ta <= tb ? [P, Q, b] : [Q, P, a];
|
||||
await runUntil(Math.max(ta, tb) + 1000);
|
||||
const owners = await db.select().from(tables.base).where(and(eq(tables.base.col, target.col), eq(tables.base.row, target.row)));
|
||||
assert.equal(owners.length, 1);
|
||||
assert.equal(owners[0].playerId, winner.playerId);
|
||||
const [rep] = await db.select().from(tables.battleReport).where(and(eq(tables.battleReport.kind, "gruendung"), eq(tables.battleReport.attackerPlayerId, loser.playerId)));
|
||||
assert.match(rep.title, /gescheitert: Feld besetzt/);
|
||||
const [m] = await db.select().from(tables.mission).where(eq(tables.mission.id, (loserMission as { missionId: number }).missionId));
|
||||
assert.equal((m.returning as Record<string, number>)[SHIP], 1);
|
||||
assert.deepEqual(m.cargoHome, { stahl: 1000 });
|
||||
await runUntil(m.returnAt!.getTime() + 1000);
|
||||
const s = await stateOf(loser.baseId);
|
||||
assert.equal(s.units[SHIP], 3, "Kolonieschiff zurück");
|
||||
assert.equal((await basesOfPlayer(db, loser.playerId)).length, 1);
|
||||
});
|
||||
|
||||
test("Verlegung: Einheiten wechseln den Hafen, Veteranen gemischt, Admiral wechselt; Transport in eigenen Hafen", async () => {
|
||||
await patchBase(A.baseId, (s) => { s.veterancy = { korvette: 20 }; s.units.landungsschiff = 2; });
|
||||
await patchBase(colonyId, (s) => { s.units = { korvette: 2 }; s.veterancy = {}; s.resUpdatedAt = Date.now(); });
|
||||
const [adm] = await db.insert(tables.admiral).values({ playerId: A.playerId, baseId: A.baseId, name: "Admiral Test", spec1: admiralSpecIds()[0] }).returning({ id: tables.admiral.id });
|
||||
const col = (await basesOfPlayer(db, A.playerId)).find((b) => b.id === colonyId)!;
|
||||
assert.equal(code(await missionPreview(engine, A.playerId, { type: "verlegung", units: { korvette: 1 }, col: A.col, row: A.row })), "same_base");
|
||||
const other = await freeCoast(A, 100, 2000);
|
||||
assert.equal(code(await missionPreview(engine, A.playerId, { type: "verlegung", units: { korvette: 1 }, ...other })), "transfer_needs_own_base");
|
||||
const pv = await missionPreview(engine, A.playerId, { type: "verlegung", units: { korvette: 6 }, col: col.col, row: col.row, admiralId: adm.id });
|
||||
assert.equal(pv.ok, true, JSON.stringify(pv));
|
||||
assert.equal((pv as { returnAtMs: number; arriveAtMs: number }).returnAtMs, (pv as { arriveAtMs: number }).arriveAtMs);
|
||||
const go = await launchMission(engine, A.playerId, key(), { type: "verlegung", units: { korvette: 6, landungsschiff: 1 }, col: col.col, row: col.row, admiralId: adm.id, cargo: { proviant: 500 } });
|
||||
assert.equal(go.ok, true, JSON.stringify(go));
|
||||
const before = await stateOf(colonyId);
|
||||
await runUntil((go as { arriveAtMs: number }).arriveAtMs + 1000);
|
||||
const to = await stateOf(colonyId);
|
||||
assert.equal(to.units.korvette, 8);
|
||||
assert.equal(to.veterancy?.korvette, (0 * 2 + 20 * 6) / 8);
|
||||
assert.ok(to.resources.proviant >= before.resources.proviant + 300, "Ladung angekommen (abzüglich Unterhalt)");
|
||||
const from = await stateOf(A.baseId);
|
||||
assert.equal(from.units.korvette, 14);
|
||||
assert.equal(from.unitsAway.korvette ?? 0, 0);
|
||||
assert.equal(from.veterancy?.korvette, 20);
|
||||
const [a] = await db.select().from(tables.admiral).where(eq(tables.admiral.id, adm.id));
|
||||
assert.equal(a.baseId, colonyId, "Admiral wechselt den Hafen");
|
||||
const [m] = await db.select().from(tables.mission).where(eq(tables.mission.id, (go as { missionId: number }).missionId));
|
||||
assert.equal(m.status, "done");
|
||||
const [rep] = await db.select().from(tables.battleReport).where(eq(tables.battleReport.id, m.reportId!));
|
||||
assert.equal(rep.kind, "verlegung");
|
||||
|
||||
// Transport in den eigenen Hafen (nicht in den Ausgangshafen).
|
||||
assert.equal(code(await missionPreview(engine, A.playerId, { type: "transport", units: { korvette: 1 }, col: A.col, row: A.row, cargo: {} })), "own_base");
|
||||
const tr = await launchMission(engine, A.playerId, key(), { type: "transport", units: { landungsschiff: 1 }, col: col.col, row: col.row, cargo: { stahl: 2000 } });
|
||||
assert.equal(tr.ok, true, JSON.stringify(tr));
|
||||
const st0 = (await stateOf(colonyId)).resources.stahl;
|
||||
await runUntil((tr as { arriveAtMs: number }).arriveAtMs + 1000);
|
||||
assert.ok((await stateOf(colonyId)).resources.stahl >= st0 + 2000 - 1, "Ladung angekommen");
|
||||
});
|
||||
|
||||
test("Saisonende löscht alle Häfen; der erste Hafen der neuen Saison ist der Heimathafen", async () => {
|
||||
const season = (await runningSeason(db))!;
|
||||
await db.transaction((tx) => seasonEnd(tx, { id: 0, type: "season_end", dueAt: new Date(), payload: { seasonId: season.id }, baseId: null }, Date.now()));
|
||||
assert.equal((await basesOfPlayer(db, A.playerId)).length, 0);
|
||||
const f = await freeCoast(null, 0, 0);
|
||||
const r = await chooseBase(engine, A.playerId, key(), { ...f, name: "Neuer Hafen", nightShieldStartHour: null, tzOffsetMinutes: 0 });
|
||||
assert.equal(r.ok, true, JSON.stringify(r));
|
||||
const home = await homeBaseOf(db, A.playerId);
|
||||
assert.equal(home?.id, (r as { baseId: number }).baseId);
|
||||
assert.equal(home?.isHome, true);
|
||||
assert.equal(home?.state.colony, undefined);
|
||||
});
|
||||
@@ -612,3 +612,29 @@ Ziel: Felder sind Entscheidungen und Konflikte, kein passiver Mehrertrag.
|
||||
7. **Offen:** kein Geleitschutz für Ertragskonvois; keine Verstärkung einer Besatzung (Rückruf und neu besetzen);
|
||||
ein Admiral, der einen Besetzungsverband führt, bleibt bei der Besatzung; Wochenziel-Art für Felder nicht umgesetzt;
|
||||
kein Radar-Vorwarnung für Angriffe auf Felder (nur Push nach dem Kampf, beim Kartell vorab).
|
||||
|
||||
## K. Mehrere Häfen: Gründung und Verlegung (Welle 3 „Expansion“, Teil 2, Block `expansion`, v1.11)
|
||||
|
||||
1. **Freischaltung.** 2. Hafen ab Kommandozentrale 8, 3. ab 14 (Heimathafen), höchstens 3; laufende Gründungen zählen
|
||||
mit. Der Wirtschafts-Bot erreicht in 28 Tagen nur Kommandozentrale 6–7 (gieriger Ausbau, billigstes zuerst); ein
|
||||
Spieler, der gezielt die Kommandozentrale baut, erreicht 8 deutlich früher. Die Stufen sind eine Vorgabe des Plans
|
||||
und bewusst eine Mittelspiel-Entscheidung, keine Startoption.
|
||||
2. **Kolonieschiff.** Kosten 6000 Stahl, 3000 Treibstoff, 2000 Elektronik, 2000 Proviant = 18 600 zum Richtwert; das
|
||||
sind 27 / 24 / 21 Stunden Produktion des Bot-Hafens an Tag 10 / 14 / 21 (689 / 779 / 894 je Stunde). Bauzeit 3 h
|
||||
(2 h bei Werft 6), Werft 6 und Hafenkommandantur 6, höchstens 0,2 je Werftstufe. Ladung 3000 für Startgüter.
|
||||
3. **Amortisation** (`sim/expansion.ts`): Der Bot baut den neuen Hafen ab dem Startbestand (1000/500/250/500) mit 20 %
|
||||
Rüstungsanteil aus. Aufsummierte Nettoproduktion Tag 1/2/3/5/7: 1 559 / 10 128 / 22 362 / 49 588 / 80 444 →
|
||||
**amortisiert nach 3 Tagen** (Kosten Schiff + 600 km Treibstoff 18 816). Mit voller Ladung (3000, gleich verteilt,
|
||||
verlegt, nicht als Kosten gezählt) nach 2 Tagen. Nach 10 Tagen produziert die Kolonie 735/h (Kommandozentrale 4) –
|
||||
etwa so viel wie der Heimathafen an Tag 10. Erster Entwurf (27 900 Richtwert) amortisierte nach 4 Tagen, kostete aber
|
||||
31–41 Stunden Produktion; gesenkt auf 2/3, damit der Bau im Mittelspiel kein Tagewerk ist und die Amortisation
|
||||
am unteren Rand des Ziels (3–5 Tage) bleibt.
|
||||
4. **Schutz.** Kolonien erben den Anfängerschutz des Heimathafens (kein neuer Anfängerschutz durch Gründen) und haben
|
||||
24 h Gründungsschutz (eigener Schutzgrund `gruendungsschutz`); erster Kartell-Überfall nach 48 h.
|
||||
5. **Abstand.** Mindestens 4 Felder zu fremden, 3 zu eigenen Häfen, höchstens 900 km vom Heimathafen; kein Nest,
|
||||
Handelshafen, Rohstofffeld. Wettlauf um ein Feld entscheidet der eindeutige Index `base_field`; der Verlierer fährt
|
||||
mit Ladung heim.
|
||||
6. **Verlegung.** Nur Hinfahrt (Treibstoff einfach), dauerhaft; Veteranen gewichtet gemischt, Admiral wechselt den
|
||||
Hafen. Transport in eigene Häfen ist erlaubt.
|
||||
7. **Offen:** „Kolonie aufgeben“ (P5); Umbenennen eines Hafens; Ortsname aus der Karte statt „<Name> II“; Auftragsbuch-
|
||||
und Wochenziel-Schritt für Gründungen.
|
||||
@@ -0,0 +1,65 @@
|
||||
// Mehrere Häfen: Kosten einer Kolonie (Kolonieschiff, Treibstoff) gegen den Ertrag des neuen Hafens. Der neue Hafen
|
||||
// wird vom Wirtschafts-Bot ab dem Startbestand (expansion.startResources plus Ladung) ausgebaut; gemessen wird die
|
||||
// aufsummierte Nettoproduktion zum Richtwert. Amortisation = Tage, bis sie die Kosten deckt (Ziel 3–5 Tage).
|
||||
import type { Balance, BaseState } from "../src/index.ts";
|
||||
import { expansionOf, fuelCost, productionRates, trainingCost } from "../src/index.ts";
|
||||
import type { BotSnapshot } from "./bot.ts";
|
||||
import { runBot, value } from "./bot.ts";
|
||||
|
||||
const STEP_H = 10 / 60;
|
||||
/** Typische Entfernung Heimathafen → neuer Hafen (km). */
|
||||
const DIST_KM = 600;
|
||||
/** Kolonien bauen zuerst die Wirtschaft aus: geringerer Rüstungsanteil als der Heimathafen. */
|
||||
const COLONY_MILITARY_SHARE = 0.2;
|
||||
|
||||
/** Nettoproduktion (Richtwert) eines neuen Hafens je Tag, aufsummiert über `days` Tage. */
|
||||
function colonyIncome(balance: Balance, cargo: Record<string, number>, days: number): { cumulative: number[]; last: BaseState } {
|
||||
const e = expansionOf(balance)!;
|
||||
const start: Record<string, number> = {};
|
||||
for (const r of balance.resources) start[r] = (e.startResources[r] ?? 0) + (cargo[r] ?? 0);
|
||||
const b: Balance = { ...balance, start };
|
||||
let sum = 0;
|
||||
const cumulative: number[] = [];
|
||||
let lastDay = 0;
|
||||
let last: BaseState | null = null;
|
||||
runBot(b, days, [], COLONY_MILITARY_SHARE, undefined, (base, t) => {
|
||||
sum += value(productionRates(base, b).perHour, b) * STEP_H;
|
||||
const day = Math.floor(t / 86400000);
|
||||
if (day > lastDay) {
|
||||
cumulative.push(sum);
|
||||
lastDay = day;
|
||||
}
|
||||
last = base;
|
||||
return base;
|
||||
});
|
||||
return { cumulative, last: last! };
|
||||
}
|
||||
|
||||
export function runExpansionSim(balance: Balance, snaps: BotSnapshot[]): void {
|
||||
const e = expansionOf(balance);
|
||||
if (!e) return;
|
||||
const shipDef = balance.units[e.colonyShip];
|
||||
const ship = value(trainingCost(e.colonyShip, 1, balance), balance);
|
||||
const fuel = fuelCost({ [e.colonyShip]: 1 }, DIST_KM, balance, undefined, 1) * (balance.market.refPrice.treibstoff ?? 0);
|
||||
const cost = ship + fuel;
|
||||
console.log(`\nMehrere Häfen: Kolonieschiff ${Math.round(ship)} (Richtwert), Treibstoff ${DIST_KM} km ${Math.round(fuel)}, ` +
|
||||
`Ladung bis ${shipDef.cargo ?? 0}, Bauzeit ${(((shipDef.seconds ?? 0) / (1 + (balance.buildings.werft.buildSpeedPerLevel ?? 0) * ((shipDef.requiresLevel ?? 1) - 1))) / 3600).toFixed(1)} h (Werft ${shipDef.requiresLevel})`);
|
||||
for (const day of [10, 14, 21]) {
|
||||
const s = snaps.find((x) => x.day === day);
|
||||
if (!s) continue;
|
||||
const prod = value(productionRates(s.base, balance).perHour, balance);
|
||||
console.log(` Bot-Hafen Tag ${day}: KZ ${s.base.buildings.kommandozentrale}, HK ${s.base.buildings.hafenkommandantur}, Werft ${s.base.buildings.werft}, ` +
|
||||
`Produktion ${Math.round(prod)}/h → Kolonieschiff = ${(cost / prod).toFixed(1)} h Produktion`);
|
||||
}
|
||||
const cargoFull: Record<string, number> = {};
|
||||
const per = Math.floor((shipDef.cargo ?? 0) / balance.resources.length);
|
||||
for (const r of balance.resources) cargoFull[r] = per;
|
||||
for (const [name, cargo] of [["ohne Ladung", {}], ["volle Ladung (gleich verteilt)", cargoFull]] as const) {
|
||||
const extra = value(cargo, balance);
|
||||
const { cumulative, last } = colonyIncome(balance, cargo, 10);
|
||||
const pay = cumulative.findIndex((c) => c >= cost);
|
||||
const prod = value(productionRates(last, balance).perHour, balance);
|
||||
console.log(` Kolonie ${name}: Ertrag Tag 1/2/3/5/7 = ${[1, 2, 3, 5, 7].map((d) => Math.round(cumulative[d - 1] ?? 0)).join(" / ")}, ` +
|
||||
`Ladung ${Math.round(extra)} (verlegt, keine Kosten) → amortisiert nach ${pay < 0 ? "> 10" : pay + 1} Tagen; Tag 10: KZ ${last.buildings.kommandozentrale}, ${Math.round(prod)}/h`);
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import { runEspionageSim } from "./espionage.ts";
|
||||
import { runAdmiralSim } from "./admirals.ts"; // Admirale
|
||||
import { runNavalSim } from "./naval.ts"; // See: Minen/Blockade/Konvoi
|
||||
import { runFieldsSim } from "./fields.ts"; // Felder
|
||||
import { runExpansionSim } from "./expansion.ts"; // Mehrere Häfen
|
||||
|
||||
const balance = JSON.parse(
|
||||
readFileSync(new URL("../../balance/v1/balance.json", import.meta.url), "utf8"),
|
||||
@@ -268,6 +269,7 @@ runAdmiralSim(balance);
|
||||
runNavalSim(balance, snaps);
|
||||
// Felder: Ertrag gegen Kosten und Risiko, Fallquote der Besatzung.
|
||||
runFieldsSim(balance, snaps);
|
||||
runExpansionSim(balance, snaps); // Mehrere Häfen
|
||||
|
||||
/** Der Bot schickt alles, was daheim steht (die Doktrin hält ihn innerhalb der Kommandopunkte). */
|
||||
function sentFleet(s: BotSnapshot): Counts {
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Balance, BaseState, BuildOrder, ResourceMap, Result } from "./type
|
||||
import { buildingLevel, hasResources, settle, subtractResources } from "./economy.ts";
|
||||
import type { Modifiers } from "./modifiers.ts";
|
||||
import { modValue } from "./modifiers.ts";
|
||||
import { homeOnlyBlocked } from "./expansion.ts";
|
||||
|
||||
/** Kosten für den Ausbau von Stufe `level` auf `level + 1`, je Ressource aufgerundet. */
|
||||
export function upgradeCost(buildingId: string, level: number, balance: Balance): ResourceMap {
|
||||
@@ -70,7 +71,8 @@ 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).
|
||||
* Codes: unknown_building, queue_full, max_level, command_cap, insufficient_resources.
|
||||
* Codes: unknown_building, home_only (nur im Heimathafen, z. B. Forschungsamt in einer Kolonie), queue_full, max_level,
|
||||
* command_cap, insufficient_resources.
|
||||
*/
|
||||
export function startUpgrade(
|
||||
base: BaseState,
|
||||
@@ -80,6 +82,7 @@ export function startUpgrade(
|
||||
mods?: Modifiers,
|
||||
): Result<{ base: BaseState; order: BuildOrder }> {
|
||||
if (!Object.hasOwn(balance.buildings, buildingId)) return { ok: false, code: "unknown_building" };
|
||||
if (homeOnlyBlocked(base, buildingId, balance)) return { ok: false, code: "home_only" };
|
||||
if (base.buildQueue.length >= balance.building.queueSlots) return { ok: false, code: "queue_full" };
|
||||
const level = plannedLevel(base, buildingId);
|
||||
if (level + 1 > balance.building.maxLevel) return { ok: false, code: "max_level" };
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
// Mehrere Häfen: Gründung eines Außenpostens per Kolonieschiff und Verlegung zwischen eigenen Häfen
|
||||
// (docs/REGELN-EXPANSION.md). Reine, deterministische Regeln; Werte aus dem Block `expansion` der Balance.
|
||||
// Fehlt der Block, gibt es keine Außenposten. Gelände, Nester, Handelshäfen und Felder liefert der Aufrufer.
|
||||
import type { Balance, BaseState, Counts, GeoPoint, ProtectionState, ResourceMap } from "./types.ts";
|
||||
import { createBase, buildingLevel } from "./economy.ts";
|
||||
import { settleNightShield } from "./protection.ts";
|
||||
import type { Veterancy } from "./veterans.ts";
|
||||
|
||||
const HOUR_MS = 3600000;
|
||||
|
||||
export interface ExpansionDef {
|
||||
/** Höchstzahl der Häfen je Spieler (Heimathafen eingeschlossen). */
|
||||
maxBases: number;
|
||||
/** Je erreichter Stufe der Kommandozentrale des Heimathafens ein weiterer Hafen (aufsteigend). */
|
||||
unlockCommandLevels: number[];
|
||||
/** Einheit, die gründet (wird verbraucht). */
|
||||
colonyShip: string;
|
||||
/** Mindestabstand in Feldern zu fremden bzw. eigenen Häfen. */
|
||||
minDistanceHex: number;
|
||||
minDistanceOwnHex: number;
|
||||
/** Höchstentfernung des neuen Hafens zum Heimathafen (km). */
|
||||
maxRangeKm: number;
|
||||
/** Gründungsschutz des neuen Hafens (Stunden). */
|
||||
colonyShieldHours: number;
|
||||
/** Erster Kartell-Überfall auf den neuen Hafen frühestens nach so vielen Stunden. */
|
||||
firstRaidAfterHours: number;
|
||||
/** Startbestand des neuen Hafens (zusätzlich zur Ladung). */
|
||||
startResources: ResourceMap;
|
||||
/** Gebäude, die nur im Heimathafen gebaut werden dürfen. */
|
||||
homeOnlyBuildings: string[];
|
||||
/** Mindeststufe der Hafenkommandantur für das Kolonieschiff. */
|
||||
harborLevelForShip: number;
|
||||
}
|
||||
|
||||
export interface HexPos {
|
||||
col: number;
|
||||
row: number;
|
||||
}
|
||||
|
||||
export function expansionOf(balance: Balance): ExpansionDef | null {
|
||||
return balance.expansion ?? null;
|
||||
}
|
||||
|
||||
/** Abstand zweier Felder in Feldschritten (Gitter „odd-r“: ungerade Zeilen um ein halbes Feld nach Osten). */
|
||||
export function hexSteps(a: HexPos, b: HexPos): number {
|
||||
const cube = (h: HexPos) => {
|
||||
const x = h.col - (h.row - (h.row & 1)) / 2;
|
||||
return { x, z: h.row, y: -x - h.row };
|
||||
};
|
||||
const p = cube(a);
|
||||
const q = cube(b);
|
||||
return Math.max(Math.abs(p.x - q.x), Math.abs(p.y - q.y), Math.abs(p.z - q.z));
|
||||
}
|
||||
|
||||
/** Erlaubte Zahl eigener Häfen: 1 + je erreichter Freischaltstufe der Kommandozentrale (Heimathafen), höchstens maxBases. */
|
||||
export function allowedBases(homeState: BaseState, balance: Balance): number {
|
||||
const e = expansionOf(balance);
|
||||
if (!e) return 1;
|
||||
const kz = buildingLevel(homeState, "kommandozentrale");
|
||||
return Math.min(e.maxBases, 1 + e.unlockCommandLevels.filter((l) => l <= kz).length);
|
||||
}
|
||||
|
||||
/** Nächste Freischaltstufe der Kommandozentrale (null: keine weitere). */
|
||||
export function nextUnlockLevel(homeState: BaseState, balance: Balance): number | null {
|
||||
const e = expansionOf(balance);
|
||||
if (!e || allowedBases(homeState, balance) >= e.maxBases) return null;
|
||||
const kz = buildingLevel(homeState, "kommandozentrale");
|
||||
return e.unlockCommandLevels.find((l) => l > kz) ?? null;
|
||||
}
|
||||
|
||||
export function colonyShipCount(units: Counts, balance: Balance): number {
|
||||
const e = expansionOf(balance);
|
||||
return e ? units[e.colonyShip] ?? 0 : 0;
|
||||
}
|
||||
|
||||
export interface FoundingCheck {
|
||||
target: HexPos;
|
||||
/** Zielfeld ist Küste (packages/world isCoast). */
|
||||
coast: boolean;
|
||||
/** Entfernung Zielfeld → Heimathafen (km). */
|
||||
homeDistanceKm: number;
|
||||
/** Alle Häfen auf der Karte; own = gehört dem Gründer. */
|
||||
bases: (HexPos & { own: boolean })[];
|
||||
nests: HexPos[];
|
||||
tradePorts: HexPos[];
|
||||
/** Positionen der Rohstofffelder. */
|
||||
fields: HexPos[];
|
||||
homeState: BaseState;
|
||||
/** Eigene Häfen (Heimathafen eingeschlossen) und laufende Gründungen. */
|
||||
ownBases: number;
|
||||
pendingFoundings: number;
|
||||
/** Verband der Gründung; fehlt er, wird das Kolonieschiff nicht geprüft (Ankunft). */
|
||||
units?: Counts;
|
||||
}
|
||||
|
||||
const same = (a: HexPos, b: HexPos) => a.col === b.col && a.row === b.row;
|
||||
|
||||
/**
|
||||
* Grund, warum auf dem Feld kein Hafen gegründet werden kann; null = frei.
|
||||
* Codes: expansion_off, command_level (nächste Freischaltung über die Kommandozentrale), base_limit, colony_ship (nicht genau
|
||||
* ein Kolonieschiff), not_coast, field_taken (Hafen oder Nest), trade_port, resource_field, too_close_own, too_close, too_far.
|
||||
*/
|
||||
export function foundingBlocker(c: FoundingCheck, balance: Balance): string | null {
|
||||
const e = expansionOf(balance);
|
||||
if (!e) return "expansion_off";
|
||||
const allowed = allowedBases(c.homeState, balance);
|
||||
if (c.ownBases + c.pendingFoundings >= allowed) return allowed < e.maxBases ? "command_level" : "base_limit";
|
||||
if (c.units && colonyShipCount(c.units, balance) !== 1) return "colony_ship";
|
||||
if (!c.coast) return "not_coast";
|
||||
if (c.bases.some((b) => same(b, c.target)) || c.nests.some((n) => same(n, c.target))) return "field_taken";
|
||||
if (c.tradePorts.some((p) => same(p, c.target))) return "trade_port";
|
||||
if (c.fields.some((f) => same(f, c.target))) return "resource_field";
|
||||
for (const b of c.bases) {
|
||||
const d = hexSteps(b, c.target);
|
||||
if (b.own && d < e.minDistanceOwnHex) return "too_close_own";
|
||||
if (!b.own && d < e.minDistanceHex) return "too_close";
|
||||
}
|
||||
if (c.homeDistanceKm > e.maxRangeKm) return "too_far";
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schutz einer neuen Kolonie: Anfängerschutz erbt den Beginn des Heimathafens (createdAtMs), dazu Gründungsschutz
|
||||
* für colonyShieldHours; die Nachtschild-Einstellung (auch eine vorgemerkte) wird übernommen.
|
||||
*/
|
||||
export function colonyProtection(home: ProtectionState, nowMs: number, balance: Balance): ProtectionState {
|
||||
const s = settleNightShield(home, nowMs);
|
||||
const hours = expansionOf(balance)?.colonyShieldHours ?? 0;
|
||||
return {
|
||||
createdAtMs: home.createdAtMs,
|
||||
nightShieldStartHour: s.nightShieldStartHour,
|
||||
tzOffsetMinutes: s.tzOffsetMinutes,
|
||||
nightShieldSuspendedUntilMs: 0,
|
||||
defeatShieldUntilMs: 0,
|
||||
foundingShieldUntilMs: nowMs + hours * HOUR_MS,
|
||||
...(s.nightShieldNext ? { nightShieldNext: { ...s.nightShieldNext } } : {}),
|
||||
...(s.nightShieldChangedAtMs !== undefined ? { nightShieldChangedAtMs: s.nightShieldChangedAtMs } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Neuer Hafen einer Gründung: leerer Stützpunkt mit Startbestand plus Ladung, Schutz nach colonyProtection. */
|
||||
export function createColony(balance: Balance, nowMs: number, site: GeoPoint, homeProtection: ProtectionState, cargo: ResourceMap = {}): BaseState {
|
||||
const state = createBase(balance, nowMs, site);
|
||||
const start = expansionOf(balance)?.startResources ?? {};
|
||||
for (const r of balance.resources) state.resources[r] = (start[r] ?? 0) + (cargo[r] ?? 0);
|
||||
state.protection = colonyProtection(homeProtection, nowMs, balance);
|
||||
state.colony = { foundedAtMs: nowMs };
|
||||
return state;
|
||||
}
|
||||
|
||||
/** Darf das Gebäude in diesem Hafen gebaut werden? (homeOnlyBuildings nur im Heimathafen, also nicht in Kolonien.) */
|
||||
export function homeOnlyBlocked(base: BaseState, buildingId: string, balance: Balance): boolean {
|
||||
return base.colony !== undefined && (expansionOf(balance)?.homeOnlyBuildings ?? []).includes(buildingId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verlegung: Erfahrung im Zielhafen nach Ankunft von `units` mit der Erfahrung `from` (Durchschnitt des Ausgangshafens).
|
||||
* Gewichtetes Mittel über den Bestand des Ziels (daheim und unterwegs). Liefert undefined, wenn nichts bleibt.
|
||||
*/
|
||||
export function mergeVeterancy(target: BaseState, from: Veterancy | undefined, units: Counts): Veterancy | undefined {
|
||||
const out: Veterancy = { ...(target.veterancy ?? {}) };
|
||||
for (const [id, n] of Object.entries(units)) {
|
||||
if (!(n > 0)) continue;
|
||||
const have = (target.units[id] ?? 0) + (target.unitsAway[id] ?? 0);
|
||||
const xp = ((out[id] ?? 0) * have + (from?.[id] ?? 0) * n) / (have + n);
|
||||
if (xp > 1e-6) out[id] = xp;
|
||||
else delete out[id];
|
||||
}
|
||||
return Object.keys(out).length > 0 ? out : undefined;
|
||||
}
|
||||
@@ -22,3 +22,4 @@ export * from "./naval.ts"; // See: Minen/Blockade/Konvoi
|
||||
export * as market from "./market/index.ts";
|
||||
export * from "./alliance-ops.ts"; // Allianz-Ops (Sammelangriff, Stationierung)
|
||||
export * from "./fields.ts"; // Felder: Rohstofffelder einnehmen
|
||||
export * from "./expansion.ts"; // Mehrere Häfen: Gründung, Verlegung
|
||||
@@ -18,6 +18,12 @@ import { modEntry, modValue } from "./modifiers.ts";
|
||||
|
||||
export const MISSION_TYPES: readonly MissionType[] = ["ueberfall", "aufklaerung", "transport"];
|
||||
|
||||
/** Mehrere Häfen: Gründung (Kolonieschiff, Geleit kehrt heim) und Verlegung (nur Hinfahrt), nur serverseitig geplant. */
|
||||
export const EXPANSION_MISSION_TYPES: readonly MissionType[] = ["gruendung", "verlegung"];
|
||||
|
||||
/** Missionsarten, die Ladung mitführen dürfen. */
|
||||
const CARGO_TYPES: readonly string[] = ["transport", "gruendung", "verlegung"];
|
||||
|
||||
/** Hin- und Rückweg (REGELN.md, Abschnitt Missionen). */
|
||||
export const ROUND_TRIP_FACTOR = 2;
|
||||
|
||||
@@ -99,14 +105,14 @@ export function travelSeconds(units: Counts, distance: number, balance: Balance,
|
||||
return (distance / speed) * 3600;
|
||||
}
|
||||
|
||||
/** Treibstoff für Hin- und Rückweg, aufgerundet (`mods.fuel` vor dem Aufrunden). */
|
||||
export function fuelCost(units: Counts, distance: number, balance: Balance, mods?: Modifiers): number {
|
||||
/** Treibstoff für Hin- und Rückweg (`trips` Strecken, Vorgabe 2), aufgerundet (`mods.fuel` vor dem Aufrunden). */
|
||||
export function fuelCost(units: Counts, distance: number, balance: Balance, mods?: Modifiers, trips = ROUND_TRIP_FACTOR): number {
|
||||
let sum = 0;
|
||||
for (const [id, n] of entries(units)) {
|
||||
sum += ((balance.units[id]?.fuelPer100Km ?? 0) * n * distance) / 100;
|
||||
}
|
||||
// Rundung auf 9 Nachkommastellen vor dem Aufrunden, damit 7.000000000001 nicht 8 kostet.
|
||||
return Math.ceil(Math.round(sum * ROUND_TRIP_FACTOR * modValue(mods, "fuel") * 1e9) / 1e9);
|
||||
return Math.ceil(Math.round(sum * trips * modValue(mods, "fuel") * 1e9) / 1e9);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -114,6 +120,9 @@ export function fuelCost(units: Counts, distance: number, balance: Balance, mods
|
||||
* (und Transportgut) ab und verschiebt die Einheiten nach unitsAway.
|
||||
* Zusätzliche Codes: bad_type, no_mission_slot, target_protected, cargo_not_allowed, bad_cargo,
|
||||
* cargo_capacity, fuel, insufficient_resources, storm (reine Luftmission bei Sturm am Start).
|
||||
* Mehrere Häfen: „gruendung“ braucht genau ein Kolonieschiff (colony_ship, ohne Balance-Block expansion_off); Treibstoff
|
||||
* für das Kolonieschiff nur hin, für das Geleit hin und zurück. „verlegung“ fährt nur hin (Treibstoff einfach,
|
||||
* returnAtMs = arriveAtMs). Beide dürfen Ladung bis zur Kapazität mitführen.
|
||||
* Wetter (`input.weather`, v1.6): Mit Schiffen verlängert der Sturm entlang der Route die Reisezeit (shipFactor).
|
||||
*/
|
||||
export function planMission(
|
||||
@@ -123,8 +132,13 @@ export function planMission(
|
||||
balance: Balance,
|
||||
mods?: Modifiers,
|
||||
): Result<{ base: BaseState; mission: Mission }> {
|
||||
if (!(MISSION_TYPES as readonly string[]).includes(input.type)) return { ok: false, code: "bad_type" };
|
||||
if (!(MISSION_TYPES as readonly string[]).includes(input.type) && !(EXPANSION_MISSION_TYPES as readonly string[]).includes(input.type)) {
|
||||
return { ok: false, code: "bad_type" };
|
||||
}
|
||||
const type = input.type as MissionType;
|
||||
const ship = balance.expansion?.colonyShip;
|
||||
if (type === "gruendung" && ship === undefined) return { ok: false, code: "expansion_off" };
|
||||
if (type === "gruendung" && (input.units[ship!] ?? 0) !== 1) return { ok: false, code: "colony_ship" };
|
||||
if (input.activeMissions >= missionSlots(base, balance)) return { ok: false, code: "no_mission_slot" };
|
||||
|
||||
const distance = distanceKm(input.origin, input.target);
|
||||
@@ -144,7 +158,7 @@ export function planMission(
|
||||
let cargoTotal = 0;
|
||||
for (const [r, amount] of Object.entries(input.cargo ?? {})) {
|
||||
if (amount === 0) continue;
|
||||
if (type !== "transport") return { ok: false, code: "cargo_not_allowed" };
|
||||
if (!CARGO_TYPES.includes(type)) return { ok: false, code: "cargo_not_allowed" };
|
||||
if (!balance.resources.includes(r) || !(amount > 0)) return { ok: false, code: "bad_cargo" };
|
||||
cargo[r] = amount;
|
||||
cargoTotal += amount;
|
||||
@@ -152,7 +166,12 @@ export function planMission(
|
||||
if (cargoTotal > fleet.check.cargoCapacity) return { ok: false, code: "cargo_capacity" };
|
||||
|
||||
const next = settle(base, nowMs, balance, mods);
|
||||
const fuel = fuelCost(input.units, distance, balance, mods);
|
||||
let fuel: number;
|
||||
if (type === "verlegung") fuel = fuelCost(input.units, distance, balance, mods, 1);
|
||||
else if (type === "gruendung") {
|
||||
const { [ship!]: one, ...escort } = input.units;
|
||||
fuel = fuelCost(escort, distance, balance, mods) + fuelCost({ [ship!]: one }, distance, balance, mods, 1);
|
||||
} else fuel = fuelCost(input.units, distance, balance, mods);
|
||||
if ((next.resources.treibstoff ?? 0) < fuel) return { ok: false, code: "fuel" };
|
||||
next.resources = subtractResources(next.resources, { treibstoff: fuel });
|
||||
if (!hasResources(next.resources, cargo)) return { ok: false, code: "insufficient_resources" };
|
||||
@@ -182,7 +201,7 @@ export function planMission(
|
||||
cargo,
|
||||
departAtMs: nowMs,
|
||||
arriveAtMs: nowMs + travelMs,
|
||||
returnAtMs: nowMs + 2 * travelMs,
|
||||
returnAtMs: type === "verlegung" ? nowMs + travelMs : nowMs + 2 * travelMs,
|
||||
...(mods?.stealth !== undefined && mods.stealth !== 1 ? { warningFactor: mods.stealth } : {}),
|
||||
...(input.weather ? { weather: { avgWind: input.weather.avgWind, storminess: input.weather.storminess, shipFactor } } : {}),
|
||||
};
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { Balance, ProtectionState } from "./types.ts";
|
||||
const HOUR_MS = 3600000;
|
||||
const DAY_MS = 24 * HOUR_MS;
|
||||
|
||||
export type ProtectionReason = "nachtschild" | "anfaengerschutz" | "niederlage";
|
||||
export type ProtectionReason = "nachtschild" | "anfaengerschutz" | "niederlage" | "gruendungsschutz";
|
||||
|
||||
export function createProtection(
|
||||
createdAtMs: number,
|
||||
@@ -128,13 +128,19 @@ export function applyDefeatShield(
|
||||
return { ...p, defeatShieldUntilMs: Math.max(p.defeatShieldUntilMs, until) };
|
||||
}
|
||||
|
||||
/** Gesamtstatus; bei mehreren Gründen in der Reihenfolge Anfängerschutz, Niederlage, Nachtschild. */
|
||||
/** Mehrere Häfen: Gründungsschutz einer neuen Kolonie (expansion.ts colonyProtection). */
|
||||
export function isFoundingShieldActive(p: ProtectionState, nowMs: number): boolean {
|
||||
return nowMs < (p.foundingShieldUntilMs ?? 0);
|
||||
}
|
||||
|
||||
/** Gesamtstatus; bei mehreren Gründen in der Reihenfolge Anfängerschutz, Gründungsschutz, Niederlage, Nachtschild. */
|
||||
export function protectionStatus(
|
||||
p: ProtectionState,
|
||||
nowMs: number,
|
||||
balance: Balance,
|
||||
): { protected: boolean; reason: ProtectionReason | null } {
|
||||
if (isBeginnerProtected(p, nowMs, balance)) return { protected: true, reason: "anfaengerschutz" };
|
||||
if (isFoundingShieldActive(p, nowMs)) return { protected: true, reason: "gruendungsschutz" };
|
||||
if (isDefeatShieldActive(p, nowMs)) return { protected: true, reason: "niederlage" };
|
||||
if (isNightShieldActive(p, nowMs, balance)) return { protected: true, reason: "nachtschild" };
|
||||
return { protected: false, reason: null };
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { EspionageBalance, IntelState } from "./espionage.ts";
|
||||
import type { CombatWeather, RouteWeather, WeatherBalance } from "./weather.ts";
|
||||
import type { PowerBalance, PowerSnapshot } from "./power.ts";
|
||||
import type { BlockadeBalance, ConvoysBalance, MinesBalance } from "./naval.ts"; // See: Minen/Blockade/Konvoi
|
||||
import type { ExpansionDef } from "./expansion.ts"; // Mehrere Häfen
|
||||
|
||||
export type ResourceMap = Record<string, number>;
|
||||
export type Counts = Record<string, number>;
|
||||
@@ -195,6 +196,8 @@ export interface Balance {
|
||||
mines?: MinesBalance;
|
||||
blockade?: BlockadeBalance;
|
||||
convoys?: ConvoysBalance;
|
||||
/** Mehrere Häfen: Gründung und Verlegung (expansion.ts); fehlt es, gibt es keine Außenposten. */
|
||||
expansion?: ExpansionDef;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Erfolge (Abzeichen) und Wochenziele
|
||||
@@ -347,8 +350,10 @@ export type Result<T> = ({ ok: true } & T) | Fail;
|
||||
// ---------------------------------------------------------------- Stützpunkt
|
||||
|
||||
export interface ProtectionState {
|
||||
/** Gründungszeitpunkt des Stützpunkts (Beginn des Anfängerschutzes). */
|
||||
/** Gründungszeitpunkt des Stützpunkts (Beginn des Anfängerschutzes; Kolonien erben den des Heimathafens). */
|
||||
createdAtMs: number;
|
||||
/** Mehrere Häfen: Gründungsschutz einer Kolonie bis zu diesem Zeitpunkt (fehlt sonst). */
|
||||
foundingShieldUntilMs?: number;
|
||||
/** Startstunde des Nachtschilds 0..23 in Ortszeit des Spielers; null = nicht gewählt. */
|
||||
nightShieldStartHour: number | null;
|
||||
/** Versatz der Ortszeit zu UTC in Minuten (z. B. 60 für MEZ). */
|
||||
@@ -404,6 +409,8 @@ export interface BaseState {
|
||||
/** Lage des Hafens für das Wetter (v1.6; fehlt sie, gilt power.ts DEFAULT_SITE) und Ladung des Speicherwerks. */
|
||||
site?: GeoPoint;
|
||||
powerStored?: number;
|
||||
/** Mehrere Häfen: nur bei Kolonien (gegründet per Kolonieschiff); fehlt im Heimathafen. */
|
||||
colony?: { foundedAtMs: number };
|
||||
}
|
||||
|
||||
export interface ProductionInfo {
|
||||
@@ -428,7 +435,8 @@ export interface GeoPoint {
|
||||
export type MissionType = "ueberfall" | "aufklaerung" | "transport"
|
||||
// See: Minen/Blockade/Konvoi – nur serverseitig geplant (naval-*.ts), nicht in MISSION_TYPES.
|
||||
| "minen" | "raeumen" | "blockade" | "abfangen" | "geleit"
|
||||
| "besetzen"; // Felder: Rohstofffeld besetzen (fields-*.ts)
|
||||
| "besetzen" // Felder: Rohstofffeld besetzen (fields-*.ts)
|
||||
| "gruendung" | "verlegung"; // Mehrere Häfen (expansion.ts): Außenposten gründen, Einheiten verlegen
|
||||
|
||||
export interface MissionInput {
|
||||
type: string;
|
||||
@@ -437,7 +445,7 @@ export interface MissionInput {
|
||||
target: GeoPoint;
|
||||
/** Anzahl bereits laufender Missionen dieses Stützpunkts. */
|
||||
activeMissions: number;
|
||||
/** Nur Transport: mitgeführte Ressourcen. */
|
||||
/** Nur Transport, Gründung, Verlegung: mitgeführte Ressourcen. */
|
||||
cargo?: ResourceMap;
|
||||
targetProtection?: ProtectionState; // Schutz des Ziels; Überfälle auf geschützte Ziele werden abgelehnt
|
||||
weather?: RouteWeather; // Wetter entlang der Route bei Abfahrt (v1.6); fehlt es, kein Wettereinfluss
|
||||
|
||||
@@ -53,7 +53,7 @@ export function aircraftSlotsUsed(base: BaseState, balance: Balance): number {
|
||||
/**
|
||||
* Startet die Ausbildung von Einheiten oder den Bau von Verteidigungsanlagen.
|
||||
* Codes: unknown_unit, bad_count, building_required, building_level (Stufe unter requiresLevel), supply_shortage, queue_busy,
|
||||
* no_aircraft_slots, insufficient_resources.
|
||||
* no_aircraft_slots, harbor_level (Kolonieschiff: Hafenkommandantur unter expansion.harborLevelForShip), insufficient_resources.
|
||||
*/
|
||||
export function startTraining(
|
||||
base: BaseState,
|
||||
@@ -77,6 +77,8 @@ export function startTraining(
|
||||
const level = buildingLevel(base, builtIn);
|
||||
if (level < 1) return { ok: false, code: "building_required" };
|
||||
if (level < (def.requiresLevel ?? 1)) return { ok: false, code: "building_level" };
|
||||
const exp = balance.expansion; // Mehrere Häfen: Kolonieschiff erst ab einer Stufe der Hafenkommandantur
|
||||
if (exp && id === exp.colonyShip && buildingLevel(base, "hafenkommandantur") < exp.harborLevelForShip) return { ok: false, code: "harbor_level" };
|
||||
if (next.versorgungsmangel) return { ok: false, code: "supply_shortage" };
|
||||
secondsEach = trainingSecondsPerUnit(id, level, balance, mods);
|
||||
} else {
|
||||
|
||||
@@ -496,7 +496,7 @@ test("Eigenschaftstest: viele Seeds und zufällige Verbände", () => {
|
||||
assert.ok(amount <= Math.max(0, (defender.resources?.[r] ?? 0) - (defender.protectedPerResource ?? 0)), context);
|
||||
lootSum += amount;
|
||||
}
|
||||
const cargo = (report.attacker.survivors.landungsschiff ?? 0) * (balance.units.landungsschiff.cargo ?? 0);
|
||||
const cargo = Object.entries(report.attacker.survivors).reduce((sum, [id, n]) => sum + n * (balance.units[id]?.cargo ?? 0), 0);
|
||||
assert.ok(lootSum <= cargo, context);
|
||||
if (report.winner === "attacker") {
|
||||
attackerWins++;
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
// Mehrere Häfen: Freischaltung, Prüfungen der Gründung, Schutz der Kolonie, Planung „gruendung“/„verlegung“,
|
||||
// Forschungsamt in der Kolonie gesperrt, Kolonieschiff nach Hafenkommandantur, Veteranen beim Verlegen.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
allowedBases, colonyProtection, createColony, createProtection, foundingBlocker, fuelCost, hexSteps, mergeVeterancy,
|
||||
nextUnlockLevel, planMission, protectionStatus, startTraining, startUpgrade, type FoundingCheck,
|
||||
} from "../src/index.ts";
|
||||
import { DAY, HOUR, T0, loadBalance, makeBase } from "./helpers.ts";
|
||||
|
||||
const balance = loadBalance();
|
||||
const e = balance.expansion!;
|
||||
const ship = e.colonyShip;
|
||||
|
||||
test("Freischaltung: 1 Hafen, ab Kommandozentrale 8 zwei, ab 14 drei, höchstens maxBases", () => {
|
||||
assert.equal(allowedBases(makeBase(balance, { buildings: { kommandozentrale: 7 } }), balance), 1);
|
||||
assert.equal(allowedBases(makeBase(balance, { buildings: { kommandozentrale: 8 } }), balance), 2);
|
||||
assert.equal(allowedBases(makeBase(balance, { buildings: { kommandozentrale: 14 } }), balance), 3);
|
||||
assert.equal(allowedBases(makeBase(balance, { buildings: { kommandozentrale: 20 } }), balance), e.maxBases);
|
||||
assert.equal(nextUnlockLevel(makeBase(balance, { buildings: { kommandozentrale: 9 } }), balance), 14);
|
||||
assert.equal(nextUnlockLevel(makeBase(balance, { buildings: { kommandozentrale: 14 } }), balance), null);
|
||||
const { expansion: _, ...off } = balance;
|
||||
assert.equal(allowedBases(makeBase(balance, { buildings: { kommandozentrale: 20 } }), off), 1);
|
||||
});
|
||||
|
||||
test("Feldschritte im Gitter (ungerade Zeilen versetzt)", () => {
|
||||
assert.equal(hexSteps({ col: 5, row: 5 }, { col: 5, row: 5 }), 0);
|
||||
assert.equal(hexSteps({ col: 5, row: 4 }, { col: 6, row: 4 }), 1);
|
||||
assert.equal(hexSteps({ col: 5, row: 4 }, { col: 5, row: 5 }), 1); // gerade Zeile: Nachbar unten rechts
|
||||
assert.equal(hexSteps({ col: 5, row: 5 }, { col: 6, row: 6 }), 1); // ungerade Zeile: Nachbar unten rechts
|
||||
assert.equal(hexSteps({ col: 0, row: 0 }, { col: 0, row: 4 }), 4);
|
||||
assert.equal(hexSteps({ col: 0, row: 0 }, { col: 4, row: 0 }), 4);
|
||||
});
|
||||
|
||||
function check(patch: Partial<FoundingCheck> = {}): FoundingCheck {
|
||||
return {
|
||||
target: { col: 50, row: 50 }, coast: true, homeDistanceKm: 500,
|
||||
bases: [{ col: 40, row: 50, own: true }], nests: [], tradePorts: [], fields: [],
|
||||
homeState: makeBase(balance, { buildings: { kommandozentrale: 8 } }), ownBases: 1, pendingFoundings: 0,
|
||||
units: { [ship]: 1, korvette: 3 }, ...patch,
|
||||
};
|
||||
}
|
||||
|
||||
test("Gründung: freies Küstenfeld erlaubt, alle Ablehnungsgründe", () => {
|
||||
assert.equal(foundingBlocker(check(), balance), null);
|
||||
assert.equal(foundingBlocker(check({ homeState: makeBase(balance, { buildings: { kommandozentrale: 7 } }) }), balance), "command_level");
|
||||
assert.equal(foundingBlocker(check({ pendingFoundings: 1 }), balance), "command_level", "laufende Gründung zählt mit");
|
||||
const kz20 = makeBase(balance, { buildings: { kommandozentrale: 20 } });
|
||||
assert.equal(foundingBlocker(check({ homeState: kz20, ownBases: 2, pendingFoundings: 1 }), balance), "base_limit");
|
||||
assert.equal(foundingBlocker(check({ homeState: kz20, ownBases: 2 }), balance), null);
|
||||
assert.equal(foundingBlocker(check({ units: { korvette: 3 } }), balance), "colony_ship");
|
||||
assert.equal(foundingBlocker(check({ units: { [ship]: 2 } }), balance), "colony_ship", "genau ein Kolonieschiff");
|
||||
assert.equal(foundingBlocker(check({ units: undefined }), balance), null, "Ankunft: Schiff prüft der Aufrufer");
|
||||
assert.equal(foundingBlocker(check({ coast: false }), balance), "not_coast");
|
||||
assert.equal(foundingBlocker(check({ nests: [{ col: 50, row: 50 }] }), balance), "field_taken");
|
||||
assert.equal(foundingBlocker(check({ bases: [{ col: 50, row: 50, own: false }] }), balance), "field_taken");
|
||||
assert.equal(foundingBlocker(check({ tradePorts: [{ col: 50, row: 50 }] }), balance), "trade_port");
|
||||
assert.equal(foundingBlocker(check({ fields: [{ col: 50, row: 50 }] }), balance), "resource_field");
|
||||
// Mindestabstand: fremd 4 Felder, eigen 3 Felder.
|
||||
assert.equal(foundingBlocker(check({ bases: [{ col: 47, row: 50, own: false }] }), balance), "too_close");
|
||||
assert.equal(foundingBlocker(check({ bases: [{ col: 46, row: 50, own: false }] }), balance), null);
|
||||
assert.equal(foundingBlocker(check({ bases: [{ col: 48, row: 50, own: true }] }), balance), "too_close_own");
|
||||
assert.equal(foundingBlocker(check({ bases: [{ col: 47, row: 50, own: true }] }), balance), null);
|
||||
// Reichweite zum Heimathafen.
|
||||
assert.equal(foundingBlocker(check({ homeDistanceKm: e.maxRangeKm + 1 }), balance), "too_far");
|
||||
assert.equal(foundingBlocker(check({ homeDistanceKm: e.maxRangeKm }), balance), null);
|
||||
const { expansion: _, ...off } = balance;
|
||||
assert.equal(foundingBlocker(check(), off), "expansion_off");
|
||||
});
|
||||
|
||||
test("Kolonie: Startbestand plus Ladung, Anfängerschutz erbt den Beginn, 24 h Gründungsschutz, Nachtschild übernommen", () => {
|
||||
const homeProt = { ...createProtection(T0 - 2 * DAY, 22, 60), nightShieldSuspendedUntilMs: T0 + HOUR, defeatShieldUntilMs: T0 + HOUR };
|
||||
const now = T0 + 10 * DAY; // Anfängerschutz des Heimathafens ist vorbei
|
||||
const c = createColony(balance, now, { lat: 50, lon: 0 }, homeProt, { stahl: 500 });
|
||||
assert.equal(c.resources.stahl, e.startResources.stahl + 500);
|
||||
assert.equal(c.resources.proviant, e.startResources.proviant);
|
||||
assert.deepEqual(c.colony, { foundedAtMs: now });
|
||||
assert.equal(c.protection.createdAtMs, homeProt.createdAtMs);
|
||||
assert.equal(c.protection.nightShieldStartHour, 22);
|
||||
assert.equal(c.protection.tzOffsetMinutes, 60);
|
||||
assert.equal(c.protection.defeatShieldUntilMs, 0);
|
||||
assert.equal(protectionStatus(c.protection, now + 23 * HOUR, balance).reason, "gruendungsschutz");
|
||||
assert.notEqual(protectionStatus(c.protection, now + 25 * HOUR, balance).reason, "gruendungsschutz");
|
||||
// Früh gegründet: Anfängerschutz des Heimathafens läuft weiter (nicht verlängert).
|
||||
const early = colonyProtection(createProtection(T0), T0 + DAY, balance);
|
||||
assert.equal(protectionStatus(early, T0 + DAY, balance).reason, "anfaengerschutz");
|
||||
assert.equal(early.createdAtMs, T0);
|
||||
// Vorgemerkte Einstellung wird übernommen.
|
||||
const pending = colonyProtection({ ...createProtection(T0), nightShieldNext: { startHour: 1, tzOffsetMinutes: 0, fromMs: T0 + 5 * DAY } }, T0 + DAY, balance);
|
||||
assert.equal(pending.nightShieldNext?.startHour, 1);
|
||||
});
|
||||
|
||||
test("Forschungsamt in der Kolonie gesperrt (home_only), im Heimathafen erlaubt", () => {
|
||||
const res = { stahl: 1e6, treibstoff: 1e6, elektronik: 1e6, proviant: 1e6 };
|
||||
const colony = { ...makeBase(balance, { resources: res }), colony: { foundedAtMs: T0 } };
|
||||
const r = startUpgrade(colony, "forschungsamt", T0, balance);
|
||||
assert.deepEqual(r, { ok: false, code: "home_only" });
|
||||
assert.equal(startUpgrade(colony, "stahlwerk", T0, balance).ok, true);
|
||||
assert.equal(startUpgrade(makeBase(balance, { resources: res }), "forschungsamt", T0, balance).ok, true);
|
||||
});
|
||||
|
||||
test("Kolonieschiff: Werft 6 und Hafenkommandantur 6, höchstens 0,2 je Werftstufe", () => {
|
||||
const res = { stahl: 1e6, treibstoff: 1e6, elektronik: 1e6, proviant: 1e6 };
|
||||
const b = (werft: number, hk: number) => makeBase(balance, { resources: res, buildings: { werft, hafenkommandantur: hk } });
|
||||
assert.equal(startTraining(b(5, 6), ship, 1, T0, balance).ok ? "ok" : (startTraining(b(5, 6), ship, 1, T0, balance) as { code: string }).code, "building_level");
|
||||
assert.deepEqual(startTraining(b(6, 5), ship, 1, T0, balance), { ok: false, code: "harbor_level" });
|
||||
assert.equal(startTraining(b(6, 6), ship, 1, T0, balance).ok, true);
|
||||
assert.deepEqual(startTraining(b(6, 6), ship, 2, T0, balance), { ok: false, code: "unit_cap" });
|
||||
assert.equal(startTraining(b(10, 6), ship, 2, T0, balance).ok, true);
|
||||
});
|
||||
|
||||
const origin = { lat: 50, lon: 0 };
|
||||
const target = { lat: 50, lon: 7 };
|
||||
|
||||
test("Planung Gründung: genau ein Kolonieschiff, Geleit, Ladung bis Kapazität, Treibstoff Schiff einfach + Geleit doppelt", () => {
|
||||
const base = makeBase(balance, { units: { [ship]: 2, korvette: 4 }, buildings: { hafenkommandantur: 6, kommandozentrale: 8 }, resources: { treibstoff: 50_000, stahl: 50_000 } });
|
||||
const input = { type: "gruendung", units: { [ship]: 1, korvette: 2 }, origin, target, activeMissions: 0, cargo: { stahl: 2000 } };
|
||||
const r = planMission(base, input, T0, balance);
|
||||
assert.ok(r.ok, JSON.stringify(r));
|
||||
const d = r.mission.distanceKm;
|
||||
assert.equal(r.mission.fuelCost, fuelCost({ korvette: 2 }, d, balance) + fuelCost({ [ship]: 1 }, d, balance, undefined, 1));
|
||||
assert.equal(r.mission.returnAtMs - T0, 2 * (r.mission.arriveAtMs - T0));
|
||||
assert.equal(r.base.unitsAway[ship], 1);
|
||||
assert.equal(r.base.resources.stahl, 48_000);
|
||||
assert.deepEqual(planMission(base, { ...input, units: { [ship]: 2 } }, T0, balance), { ok: false, code: "colony_ship" });
|
||||
assert.deepEqual(planMission(base, { ...input, units: { korvette: 2 } }, T0, balance), { ok: false, code: "colony_ship" });
|
||||
const cap = balance.units[ship].cargo!;
|
||||
assert.deepEqual(planMission(base, { ...input, units: { [ship]: 1 }, cargo: { stahl: cap + 1 } }, T0, balance), { ok: false, code: "cargo_capacity" });
|
||||
});
|
||||
|
||||
test("Planung Verlegung: nur Hinfahrt, Treibstoff einfach, Ladung erlaubt", () => {
|
||||
const base = makeBase(balance, { units: { korvette: 4, zerstoerer: 2 }, resources: { treibstoff: 50_000 } });
|
||||
const r = planMission(base, { type: "verlegung", units: { korvette: 4, zerstoerer: 2 }, origin, target, activeMissions: 0 }, T0, balance);
|
||||
assert.ok(r.ok, JSON.stringify(r));
|
||||
assert.equal(r.mission.fuelCost, fuelCost({ korvette: 4, zerstoerer: 2 }, r.mission.distanceKm, balance, undefined, 1));
|
||||
assert.equal(r.mission.returnAtMs, r.mission.arriveAtMs);
|
||||
assert.deepEqual(planMission(base, { type: "aufklaerung", units: { korvette: 1 }, origin, target, activeMissions: 0, cargo: { stahl: 1 } }, T0, balance), { ok: false, code: "cargo_not_allowed" });
|
||||
});
|
||||
|
||||
test("Verlegung mischt Veteranen gewichtet mit dem Bestand des Ziels", () => {
|
||||
const to = makeBase(balance, { units: { korvette: 3 }, unitsAway: { korvette: 1 }, veterancy: { korvette: 10, zerstoerer: 5 } });
|
||||
const v = mergeVeterancy(to, { korvette: 30, uboot: 8 }, { korvette: 4, uboot: 2 });
|
||||
assert.equal(v?.korvette, (10 * 4 + 30 * 4) / 8);
|
||||
assert.equal(v?.zerstoerer, 5, "andere Typen unverändert");
|
||||
assert.equal(v?.uboot, 8, "neuer Typ übernimmt die Erfahrung");
|
||||
assert.equal(mergeVeterancy(makeBase(balance), undefined, { korvette: 2 }), undefined);
|
||||
});
|
||||
Reference in new issue
Block a user