mirror of
https://github.com/db9979/tidefront.git
synced 2026-12-06 04:44:09 +01:00
Rohstofffelder einnehmen (Welle 3, Teil 1)
Felder auf See (Ölfeld, Erzbucht, Fischgrund, Elektronik-Wrack, Stufen 1-3), deterministisch aus fester Kandidatenliste, bevorzugt zwischen Häfen, Mindestabstand zum Hafen. Aufklärung und neue Missionsart Besetzen gegen Kartell-Wache oder Besatzung; Besatzung belegt einen Missionsplatz, Rückruf macht das Feld neutral. Ertrag alle 4 h als Konvoi zum Heimathafen (abfangbar, Blockade hält zurück), Unterhalt in Proviant, Höchstzahl nach Hafenkommandantur, abnehmender Ertrag, Kartellangriffe, Allianz-Einflusszonen mit Bonus und Feldpunkten. Karte, Infoblatt, Meine Felder, Planung, Legende, Handbuch, Erfolg Landnahme, Simulation sim/fields.ts, Regeln docs/REGELN-FELDER.md, Schema schema/fields.ts (ohne Migration).
This commit is contained in:
1 parent
8e022a63e6
commit
cd48accfc3
42 files changed
+1862
-30
No files matched your search
@@ -42,6 +42,7 @@ import { applyPendingBoost } from "./guide.ts";
|
||||
import { admiralForLaunch, assignAdmiral } from "./admirals-core.ts"; // Admirale
|
||||
import { STATION_TYPE, stationLaunch } from "./alliance-ops-station.ts"; // Allianz-Ops: Stationierung
|
||||
import { createConvoy, isNavalInput, launchNaval, tradeBlocked, transportConvoyRecall } from "./naval.ts"; // See: Minen/Blockade/Konvoi
|
||||
import { launchField } from "./fields-missions.ts"; // Felder
|
||||
|
||||
export type Rejected = { ok: false; code: string };
|
||||
type Draft<T> = T | (Rejected & { keepWrites?: boolean });
|
||||
@@ -238,10 +239,11 @@ export function launchMission(
|
||||
engine: Engine,
|
||||
playerId: number,
|
||||
key: string,
|
||||
input: { type: string; units: Counts; col: number; row: number; cargo?: ResourceMap; eventId?: number; admiralId?: number; blockadeId?: number; convoyId?: number; holdHours?: number },
|
||||
input: { type: string; units: Counts; col: number; row: number; cargo?: ResourceMap; eventId?: number; admiralId?: number; blockadeId?: number; convoyId?: number; holdHours?: number; fieldId?: number; stayAll?: boolean },
|
||||
) {
|
||||
return runCommand<{ ok: true; missionId: number; arriveAtMs: number }>(engine, playerId, key, "mission", async (ctx) => {
|
||||
const b = await ownBaseLocked(ctx);
|
||||
if (input.fieldId !== undefined) return launchField(ctx.tx, playerId, b, { ...input, fieldId: input.fieldId }, ctx.nowMs, ctx.notify); // Felder
|
||||
// Weltereignis als Ziel (world-events-missions.ts).
|
||||
if (input.eventId !== undefined) return launchAgainstEvent(ctx.tx, playerId, b, { ...input, eventId: input.eventId }, ctx.nowMs, ctx.notify);
|
||||
if (input.type === STATION_TYPE) return stationLaunch(ctx.tx, playerId, b, input, ctx.nowMs, ctx.notify); // Allianz-Ops
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
// Felder: Rohstofffelder auf See (docs/REGELN-FELDER.md) – Auswahl der aktiven Felder aus der festen Kandidatenliste,
|
||||
// gemeinsame Abfragen (Rang, Zonen, Allianz) und das Lesemodell für Karte und „Meine Felder“.
|
||||
// Felder hängen am Spieler UND an einem Heimathafen (baseId): Ziel der Ertragskonvois (vorbereitet für mehrere Häfen).
|
||||
import { and, desc, eq, inArray, isNotNull, sql } from "drizzle-orm";
|
||||
import {
|
||||
fieldBaseYield, fieldsOf, fieldYield, fieldZones, maxFieldsFor, yieldFactor,
|
||||
type Counts, type FieldsBalance, type ResourceMap,
|
||||
} from "@tidefront/game-core";
|
||||
import { fieldSites, hexCenter, hexDistanceKm, type FieldSite } from "@tidefront/world";
|
||||
import { tables, type DbOrTx } from "@tidefront/db";
|
||||
import { balance, type Engine } from "./context.ts";
|
||||
import { baseOfPlayer } from "./store.ts";
|
||||
import { relationsOf } from "./alliance-core.ts";
|
||||
|
||||
export const FIELD_TYPE = "besetzen";
|
||||
export const HOUR_MS = 3600000;
|
||||
|
||||
export interface FieldRow {
|
||||
id: number;
|
||||
siteIndex: number;
|
||||
col: number;
|
||||
row: number;
|
||||
kind: string;
|
||||
tier: number;
|
||||
ownerId: number | null;
|
||||
baseId: number | null;
|
||||
missionId: number | null;
|
||||
guard: unknown;
|
||||
guardAt: Date | null;
|
||||
capturedAt: Date | null;
|
||||
lastTickAt: Date | null;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
/** Anzeigenamen der Feldarten. */
|
||||
export const FIELD_KIND_TEXT: Record<string, string> = {
|
||||
oelfeld: "Ölfeld", erzbucht: "Erzbucht", fischgrund: "Fischgrund", elektronikwrack: "Elektronik-Wrack",
|
||||
};
|
||||
export const fieldName = (f: { kind: string; tier: number }) => `${FIELD_KIND_TEXT[f.kind] ?? f.kind} (Stufe ${f.tier})`;
|
||||
|
||||
export function rules(): FieldsBalance | null {
|
||||
return fieldsOf(balance);
|
||||
}
|
||||
|
||||
export function sitesOf(f: FieldsBalance): FieldSite[] {
|
||||
return fieldSites(f.siteSeed, Object.fromEntries(Object.entries(f.kinds).map(([k, v]) => [k, v.share])), f.tierShares);
|
||||
}
|
||||
|
||||
export async function fieldById(db: DbOrTx, id: number, lock = false): Promise<FieldRow | null> {
|
||||
const q = db.select().from(tables.resourceField).where(eq(tables.resourceField.id, id));
|
||||
const [r] = lock ? await q.for("update") : await q;
|
||||
return (r as FieldRow) ?? null;
|
||||
}
|
||||
|
||||
/** Eigene Felder in Einnahme-Reihenfolge (Rang für den abnehmenden Ertrag). */
|
||||
export async function ownedBy(db: DbOrTx, playerId: number): Promise<FieldRow[]> {
|
||||
const rows = await db.select().from(tables.resourceField).where(eq(tables.resourceField.ownerId, playerId));
|
||||
return (rows as FieldRow[]).sort((a, b) => (a.capturedAt?.getTime() ?? 0) - (b.capturedAt?.getTime() ?? 0) || a.id - b.id);
|
||||
}
|
||||
|
||||
/** Höchstzahl eigener Felder nach Stufe der Hafenkommandantur des Heimathafens. */
|
||||
export function maxFieldsOf(state: { buildings: Record<string, number> }): number {
|
||||
return maxFieldsFor(state.buildings.hafenkommandantur ?? 0, balance);
|
||||
}
|
||||
|
||||
/** Allianz je Spieler (nur Mitglieder). */
|
||||
export async function allianceMap(db: DbOrTx): Promise<Map<number, number>> {
|
||||
const rows = await db.select({ playerId: tables.allianceMember.playerId, allianceId: tables.allianceMember.allianceId }).from(tables.allianceMember);
|
||||
return new Map(rows.map((r) => [r.playerId, r.allianceId]));
|
||||
}
|
||||
|
||||
/** Zonen aller besetzten Felder (Feld-ID → Zone, Größe, Bonus). */
|
||||
export async function zonesOf(db: DbOrTx, fields: FieldRow[]) {
|
||||
const am = await allianceMap(db);
|
||||
return fieldZones(
|
||||
fields.filter((f) => f.ownerId !== null).map((f) => ({ id: f.id, allianceId: am.get(f.ownerId!) ?? null, at: hexCenter(f.col, f.row) })),
|
||||
balance,
|
||||
);
|
||||
}
|
||||
|
||||
/** Wache vorhanden (neutrales Feld vom Kartell gehalten)? */
|
||||
export function guarded(f: FieldRow): boolean {
|
||||
return Object.values((f.guard as Counts) ?? {}).some((n) => n > 0);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Auswahl der aktiven Felder
|
||||
|
||||
/**
|
||||
* Hält die Zahl der aktiven Felder bei `count`: neutrale Felder zu nah an einem Hafen verschwinden, ebenso neutrale
|
||||
* Felder ohne Hafen in der Nähe (älter als ein Tag), wenn es bessere Plätze gibt. Neue Felder bevorzugt dort, wo
|
||||
* Häfen mehrerer Spieler in Reichweite liegen (zwischen den Häfen), nie näher als minKmFromBase an einem Hafen.
|
||||
*/
|
||||
export async function spawnFields(db: DbOrTx, nowMs: number): Promise<number> {
|
||||
const f = rules();
|
||||
if (!f) return 0;
|
||||
const sites = sitesOf(f);
|
||||
const bases = await db.select({ col: tables.base.col, row: tables.base.row, playerId: tables.base.playerId }).from(tables.base);
|
||||
const existing = (await db.select().from(tables.resourceField)) as FieldRow[];
|
||||
const aimed = new Set((await db
|
||||
.select({ id: tables.mission.targetId })
|
||||
.from(tables.mission)
|
||||
.where(and(eq(tables.mission.targetKind, "field"), eq(tables.mission.status, "outbound")))).map((r) => r.id));
|
||||
const nearest = (h: { col: number; row: number }) => bases.reduce((m, b) => Math.min(m, hexDistanceKm(b, h)), Infinity);
|
||||
const score = (h: { col: number; row: number }) =>
|
||||
Math.min(3, new Set(bases.filter((b) => hexDistanceKm(b, h) <= f.preferKm).map((b) => b.playerId)).size);
|
||||
const used = new Set(existing.map((e) => e.siteIndex));
|
||||
const free = sites
|
||||
.filter((s) => !used.has(s.index) && nearest(s) >= f.minKmFromBase)
|
||||
.map((s) => ({ s, score: score(s) }))
|
||||
.sort((a, b) => b.score - a.score || a.s.index - b.s.index);
|
||||
const betterExists = free.some((c) => c.score > 0);
|
||||
const drop = existing.filter((e) => e.ownerId === null && !aimed.has(e.id) && (
|
||||
nearest(e) < f.minKmFromBase || (betterExists && score(e) === 0 && nowMs - e.createdAt.getTime() > 24 * HOUR_MS)));
|
||||
if (drop.length > 0) await db.delete(tables.resourceField).where(inArray(tables.resourceField.id, drop.map((d) => d.id)));
|
||||
const need = f.count - (existing.length - drop.length);
|
||||
const add = free.slice(0, Math.max(0, need));
|
||||
if (add.length > 0) {
|
||||
await db.insert(tables.resourceField).values(add.map(({ s }) => ({
|
||||
siteIndex: s.index, col: s.col, row: s.row, kind: s.kind, tier: s.tier,
|
||||
guard: { ...(f.guard[s.tier - 1] ?? {}) }, createdAt: new Date(nowMs),
|
||||
}))).onConflictDoNothing();
|
||||
}
|
||||
return add.length;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Lesemodell
|
||||
|
||||
/** Letztes Lagebild je Feld aus eigenen Aufklärungsberichten. */
|
||||
async function intelOf(db: DbOrTx, playerId: number) {
|
||||
const rows = await db
|
||||
.select({ report: tables.battleReport.report, createdAt: tables.battleReport.createdAt })
|
||||
.from(tables.battleReport)
|
||||
.where(and(eq(tables.battleReport.attackerPlayerId, playerId), eq(tables.battleReport.kind, "aufklaerung"), sql`${tables.battleReport.report} ? 'field'`))
|
||||
.orderBy(desc(tables.battleReport.createdAt))
|
||||
.limit(300);
|
||||
const out = new Map<number, { atMs: number; units: Counts; owner: string | null }>();
|
||||
for (const r of rows) {
|
||||
const fld = (r.report as { field?: { id: number; units?: Counts; owner?: string | null } }).field;
|
||||
if (fld && !out.has(fld.id)) out.set(fld.id, { atMs: r.createdAt.getTime(), units: fld.units ?? {}, owner: fld.owner ?? null });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Besatzungen (aktueller Bestand) je Missions-ID. */
|
||||
export async function garrisons(db: DbOrTx, missionIds: number[]): Promise<Map<number, Counts>> {
|
||||
if (missionIds.length === 0) return new Map();
|
||||
const rows = await db.select({ id: tables.mission.id, returning: tables.mission.returning }).from(tables.mission).where(inArray(tables.mission.id, missionIds));
|
||||
return new Map(rows.map((r) => [r.id, (r.returning as Counts | null) ?? {}]));
|
||||
}
|
||||
|
||||
/** Nächster Lieferzyklus (geplantes field_tick). */
|
||||
export async function nextTickMs(db: DbOrTx): Promise<number | null> {
|
||||
const [e] = await db
|
||||
.select({ dueAt: tables.gameEvent.dueAt })
|
||||
.from(tables.gameEvent)
|
||||
.where(and(eq(tables.gameEvent.type, "field_tick"), eq(tables.gameEvent.status, "pending")))
|
||||
.orderBy(tables.gameEvent.dueAt)
|
||||
.limit(1);
|
||||
return e?.dueAt.getTime() ?? null;
|
||||
}
|
||||
|
||||
/** Karte und „Meine Felder“: alle Felder mit Besitzerfarbe, bekannte Besatzung, Zonen; eigene mit Ertrag. */
|
||||
export async function fieldsView(engine: Engine, playerId: number) {
|
||||
const nowMs = Date.now();
|
||||
const f = rules();
|
||||
if (!f) return null;
|
||||
const db = engine.db;
|
||||
const rows = ((await db.select().from(tables.resourceField)) as FieldRow[]).sort((a, b) => a.id - b.id);
|
||||
const relations = await relationsOf(db, playerId, nowMs);
|
||||
const names = new Map((await db.select({ id: tables.player.id, name: tables.player.name }).from(tables.player)
|
||||
.where(inArray(tables.player.id, [0, ...rows.map((r) => r.ownerId ?? 0)]))).map((p) => [p.id, p.name]));
|
||||
const zones = await zonesOf(db, rows);
|
||||
const intel = await intelOf(db, playerId);
|
||||
const garrison = await garrisons(db, rows.filter((r) => r.missionId !== null).map((r) => r.missionId!));
|
||||
const own = await baseOfPlayer(db, playerId);
|
||||
const mine = await ownedBy(db, playerId);
|
||||
const rank = new Map(mine.map((m, i) => [m.id, i]));
|
||||
const next = await nextTickMs(db);
|
||||
const relationOf = (r: FieldRow) => r.ownerId === null ? (guarded(r) ? "kartell" : "frei")
|
||||
: r.ownerId === playerId ? "own" : relations.get(r.ownerId) ?? "neutral";
|
||||
const fields = rows.map((r) => {
|
||||
const relation = relationOf(r);
|
||||
const open = relation === "own" || relation === "allianz";
|
||||
const known = intel.get(r.id);
|
||||
const z = zones.get(r.id);
|
||||
return {
|
||||
id: r.id, col: r.col, row: r.row, kind: r.kind, tier: r.tier, relation,
|
||||
owner: r.ownerId !== null ? names.get(r.ownerId) ?? "?" : null,
|
||||
yieldPerHour: fieldBaseYield(r.kind, r.tier, balance),
|
||||
garrison: open && r.missionId !== null ? garrison.get(r.missionId) ?? {} : null,
|
||||
guard: r.ownerId === null ? (open || known ? (r.guard as Counts) : null) : null,
|
||||
guardAtMs: r.ownerId === null && !guarded(r) && r.guardAt ? r.guardAt.getTime() : null,
|
||||
intel: known && !open ? { atMs: known.atMs, units: known.units, owner: known.owner } : null,
|
||||
zone: z ? { id: z.zone, size: z.size, bonus: z.bonus } : null,
|
||||
};
|
||||
});
|
||||
const minePart = mine.map((m) => {
|
||||
const z = zones.get(m.id);
|
||||
const i = rank.get(m.id)!;
|
||||
return {
|
||||
id: m.id, col: m.col, row: m.row, kind: m.kind, tier: m.tier, missionId: m.missionId,
|
||||
garrison: m.missionId !== null ? garrison.get(m.missionId) ?? {} : {},
|
||||
factor: yieldFactor(i, balance), zoneBonus: !!z?.bonus,
|
||||
yieldPerHour: fieldYield(m.kind, m.tier, 1, i, !!z?.bonus, balance) as ResourceMap,
|
||||
upkeepPerHour: f.upkeepProviantPerHour[m.tier - 1] ?? 0,
|
||||
home: m.baseId === own?.id ? own?.name ?? null : null,
|
||||
capturedAtMs: m.capturedAt?.getTime() ?? null,
|
||||
};
|
||||
});
|
||||
const am = await allianceMap(db);
|
||||
const myAlliance = am.get(playerId);
|
||||
const [score] = myAlliance !== undefined ? await db.select().from(tables.fieldScore).where(eq(tables.fieldScore.allianceId, myAlliance)) : [];
|
||||
return {
|
||||
serverNow: nowMs,
|
||||
maxFields: own ? maxFieldsOf(own.state) : 0,
|
||||
nextDeliveryAtMs: next,
|
||||
fields,
|
||||
mine: minePart,
|
||||
alliancePoints: score ? Math.round(score.points) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Besetzte Felder mit Besitzer (für Allianzwertung und Tests). */
|
||||
export async function ownedFields(db: DbOrTx): Promise<FieldRow[]> {
|
||||
return (await db.select().from(tables.resourceField).where(isNotNull(tables.resourceField.ownerId))) as FieldRow[];
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
// Felder: Missionen gegen Rohstofffelder (Missionsziel „field“): Aufklärung und „Besetzen“ (neutral: Kampf gegen die
|
||||
// Kartell-Wache; besetzt: Angriff auf die Besatzung). Nach Sieg bleibt eine Besatzung (Mission „stationed“), der Rest
|
||||
// fährt heim. Rückruf der Besatzung: Feld wird neutral. Eingehängt über markierte Eingriffe (Felder) in commands.ts
|
||||
// (launchMission), views.ts (missionPreview) und handlers.ts (missionArrive). Regeln: docs/REGELN-FELDER.md.
|
||||
import { eq } from "drizzle-orm";
|
||||
import {
|
||||
activeUnits, garrisonCheck, guardDefender, resolveBattle, splitGarrison, strandTroops,
|
||||
type AttackerInput, type Counts, type DefenderInput, type Mission,
|
||||
} from "@tidefront/game-core";
|
||||
import { hexDistanceKm } from "@tidefront/world";
|
||||
import { tables, type DbOrTx, type Tx } from "@tidefront/db";
|
||||
import { balance, GameError, type Engine, type NoticeJob } from "./context.ts";
|
||||
import { activeMissionCount, randomSeed, readBase, saveBase, scheduleEvent, withSite, type BaseRow } from "./store.ts";
|
||||
import { modifiersFor, modsOf } from "./modifiers.ts";
|
||||
import { battleWeather, missionWeather } from "./weather.ts";
|
||||
import { diplomacyBlock, systemMessage } from "./alliance-core.ts";
|
||||
import { runCommand } from "./commands.ts";
|
||||
import { recordAchievement } from "./achievements.ts";
|
||||
import {
|
||||
activeCounts, hasShips, insertMission, planNaval, playerName, pushNotice, sendHome, storeNavalReport,
|
||||
type MissionRowLike, type Notes,
|
||||
} from "./naval-common.ts";
|
||||
import { FIELD_TYPE, HOUR_MS, fieldById, fieldName, guarded, maxFieldsOf, ownedBy, rules, type FieldRow } from "./fields-core.ts";
|
||||
import { settleField } from "./fields-run.ts";
|
||||
|
||||
export interface FieldInput {
|
||||
type: string;
|
||||
units: Counts;
|
||||
fieldId: number;
|
||||
/** Ganzer siegreicher Verband bleibt als Besatzung (sonst nur die Mindestbesatzung). */
|
||||
stayAll?: boolean;
|
||||
}
|
||||
|
||||
/** Prüfungen und Planung. Codes: no_field, bad_type, own_field, field_limit, field_ships_only, garrison_too_weak, ally, pact … */
|
||||
async function planField(db: DbOrTx, playerId: number, own: BaseRow, input: FieldInput, nowMs: number) {
|
||||
const f = rules();
|
||||
if (!f) throw new GameError("bad_type");
|
||||
const field = await fieldById(db, input.fieldId);
|
||||
if (!field) throw new GameError("no_field");
|
||||
let targetProtection;
|
||||
if (input.type === FIELD_TYPE) {
|
||||
if (field.ownerId === playerId) throw new GameError("own_field");
|
||||
const g = garrisonCheck(activeCounts(input.units), balance);
|
||||
if (!g.ok) throw new GameError(g.code);
|
||||
if ((await ownedBy(db, playerId)).length >= maxFieldsOf(own.state)) throw new GameError("field_limit");
|
||||
if (field.ownerId !== null) {
|
||||
const d = await diplomacyBlock(db, playerId, field.ownerId, nowMs);
|
||||
if (d) throw new GameError(d);
|
||||
// Schutzregeln wie beim Überfall: Schutz des Heimathafens des Besitzers.
|
||||
const home = field.baseId !== null ? await readBase(db, field.baseId) : null;
|
||||
if (home) targetProtection = withSite(home.state, home.col, home.row).protection;
|
||||
}
|
||||
} else if (input.type !== "aufklaerung") throw new GameError("bad_type");
|
||||
const r = planNaval(own, {
|
||||
type: input.type as Mission["type"], baseType: input.type === FIELD_TYPE ? "ueberfall" : "aufklaerung", units: input.units,
|
||||
col: field.col, row: field.row, activeMissions: await activeMissionCount(db, own.id), mods: await modsOf(db, own, nowMs), targetProtection,
|
||||
}, nowMs);
|
||||
return { r, field };
|
||||
}
|
||||
|
||||
/** launchMission mit fieldId (Hafen aus dem Kommando-Kontext, bereits gesperrt). */
|
||||
export async function launchField(tx: Tx, playerId: number, own: BaseRow, input: FieldInput, nowMs: number, notify: Notes) {
|
||||
const { r, field } = await planField(tx, playerId, own, input, nowMs);
|
||||
if (!r.ok) return r;
|
||||
await saveBase(tx, own.id, r.base);
|
||||
const plan = input.type === FIELD_TYPE ? { ...r.mission, stayAll: !!input.stayAll } : r.mission;
|
||||
const missionId = await insertMission(tx, { playerId, baseId: own.id, targetKind: "field", targetId: field.id, col: field.col, row: field.row, plan });
|
||||
notify.push([[playerId], "base"], [[playerId], "missions"]);
|
||||
return { ok: true as const, missionId, arriveAtMs: r.mission.arriveAtMs };
|
||||
}
|
||||
|
||||
/** missionPreview mit fieldId. */
|
||||
export async function previewField(db: DbOrTx, playerId: number, own: BaseRow, input: FieldInput, nowMs: number) {
|
||||
const field = await fieldById(db, input.fieldId);
|
||||
const distanceKm = field ? hexDistanceKm(own, field) : 0;
|
||||
try {
|
||||
const { r } = await planField(db, playerId, own, input, nowMs);
|
||||
if (!r.ok) return { ok: false as const, code: r.code, distanceKm };
|
||||
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: "field", own: false }, intercept: null,
|
||||
weather: field ? missionWeather(own.col, own.row, field.col, field.row, nowMs) : null, weatherFactor: m.weather?.shipFactor ?? 1,
|
||||
};
|
||||
} catch (err) {
|
||||
if (err instanceof GameError) return { ok: false as const, code: err.code, distanceKm };
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Besatzung einer Mission auflösen (vernichtet oder nach Niederlage heim mit den Überlebenden). */
|
||||
export async function endGarrison(tx: Tx, missionId: number | null, survivors: Counts, due: number): Promise<void> {
|
||||
if (missionId === null) return;
|
||||
const [m] = await tx.select().from(tables.mission).where(eq(tables.mission.id, missionId)).for("update");
|
||||
if (!m || m.status !== "stationed") return;
|
||||
const plan = m.plan as Mission;
|
||||
const left = activeUnits(survivors);
|
||||
const returnAt = Object.keys(left).length === 0 ? due : due + Math.max(0, plan.arriveAtMs - plan.departAtMs);
|
||||
await tx.update(tables.mission).set({ status: "returning", returning: left, cargoHome: {}, returnAt: new Date(returnAt) }).where(eq(tables.mission.id, m.id));
|
||||
await scheduleEvent(tx, "mission_return", returnAt, { missionId: m.id }, m.baseId);
|
||||
}
|
||||
|
||||
/** Feld wird neutral (ohne Wache bis guardAt bzw. mit der angegebenen Wache). */
|
||||
export async function releaseField(tx: Tx, f: FieldRow, due: number, guard: Counts | null): Promise<void> {
|
||||
const r = rules()!;
|
||||
await tx.update(tables.resourceField).set({
|
||||
ownerId: null, baseId: null, missionId: null, capturedAt: null, lastTickAt: null,
|
||||
guard: guard ?? {}, guardAt: guard ? null : new Date(due + r.guardRespawnHours * HOUR_MS),
|
||||
}).where(eq(tables.resourceField.id, f.id));
|
||||
}
|
||||
|
||||
function wreckAt(tx: Tx, f: FieldRow, wreck: { stahl?: number; elektronik?: number }, due: number) {
|
||||
if ((wreck.stahl ?? 0) + (wreck.elektronik ?? 0) <= 0) return Promise.resolve();
|
||||
return tx.insert(tables.wreck).values({ col: f.col, row: f.row, stahl: wreck.stahl ?? 0, elektronik: wreck.elektronik ?? 0, createdAt: new Date(due) }).then(() => undefined);
|
||||
}
|
||||
|
||||
/** Besatzung bilden: ursprüngliche Mission bleibt (stationed), Überzählige fahren als eigene Mission heim. */
|
||||
async function stationGarrison(tx: Tx, m: MissionRowLike, plan: Mission, garrison: Counts, rest: Counts, due: number): Promise<void> {
|
||||
const travel = Math.max(0, plan.arriveAtMs - plan.departAtMs);
|
||||
const kept: Counts = {};
|
||||
for (const [id, n] of Object.entries(plan.units)) {
|
||||
const k = n - (rest[id] ?? 0);
|
||||
if (k > 0) kept[id] = k; // Besatzung plus Verluste bleiben auf dieser Mission (unitsAway stimmt bei der Rückkehr)
|
||||
}
|
||||
await tx.update(tables.mission).set({ status: "stationed", plan: { ...plan, units: kept }, returning: garrison, cargoHome: {} }).where(eq(tables.mission.id, m.id));
|
||||
if (Object.keys(rest).length === 0) return;
|
||||
const back = due + travel;
|
||||
const [r] = await tx.insert(tables.mission).values({
|
||||
playerId: m.playerId, baseId: m.baseId, type: FIELD_TYPE, targetKind: "field", targetId: m.targetId, targetCol: m.targetCol, targetRow: m.targetRow,
|
||||
plan: { ...plan, units: rest, admiralId: undefined }, status: "returning", returning: rest, cargoHome: {}, arriveAt: new Date(due), returnAt: new Date(back),
|
||||
}).returning({ id: tables.mission.id });
|
||||
await scheduleEvent(tx, "mission_return", back, { missionId: r.id }, m.baseId);
|
||||
}
|
||||
|
||||
/** mission_arrive mit targetKind "field". */
|
||||
export async function fieldArrive(tx: Tx, m: MissionRowLike, plan: Mission, origin: BaseRow | null, due: number, notify: Notes, push: NoticeJob[]): Promise<void> {
|
||||
const pid = m.playerId!;
|
||||
const field = m.targetId !== null ? await fieldById(tx, m.targetId, true) : null;
|
||||
const units = activeCounts(plan.units);
|
||||
if (!field) {
|
||||
const reportId = await storeNavalReport(tx, { kind: "feld", title: "Feld nicht mehr vorhanden", attackerPlayerId: pid, defenderPlayerId: null, attackerBaseId: m.baseId, report: { field: { gone: true } }, atMs: due });
|
||||
await sendHome(tx, m, plan, units, {}, reportId, due);
|
||||
return;
|
||||
}
|
||||
const name = fieldName(field);
|
||||
const garrison = field.missionId !== null ? (await tx.select({ returning: tables.mission.returning }).from(tables.mission).where(eq(tables.mission.id, field.missionId)))[0] : undefined;
|
||||
const garrisonUnits = activeUnits((garrison?.returning as Counts | null) ?? {});
|
||||
const ownerName = field.ownerId !== null ? await playerName(tx, field.ownerId) : null;
|
||||
if (m.type === "aufklaerung") {
|
||||
const reportId = await storeNavalReport(tx, {
|
||||
kind: "aufklaerung", title: `Aufklärung: ${name}`, attackerPlayerId: pid, defenderPlayerId: null, attackerBaseId: m.baseId, atMs: due,
|
||||
report: { field: { id: field.id, kind: field.kind, tier: field.tier, owner: ownerName, units: field.ownerId !== null ? garrisonUnits : activeUnits(field.guard as Counts) } },
|
||||
});
|
||||
await sendHome(tx, m, plan, units, {}, reportId, due);
|
||||
return;
|
||||
}
|
||||
// Besetzen: Ziel noch angreifbar?
|
||||
const refused = field.ownerId === pid ? "own_field" : field.ownerId !== null ? await diplomacyBlock(tx, pid, field.ownerId, due) : null;
|
||||
if (refused || !hasShips(units)) {
|
||||
const reportId = await storeNavalReport(tx, { kind: "feld", title: `${name}: nicht besetzt`, attackerPlayerId: pid, defenderPlayerId: null, attackerBaseId: m.baseId, report: { field: { id: field.id, refused: refused ?? "fleet_lost" } }, atMs: due });
|
||||
await sendHome(tx, m, plan, units, {}, reportId, due);
|
||||
return;
|
||||
}
|
||||
const defenderUnits = field.ownerId !== null ? garrisonUnits : activeUnits(field.guard as Counts);
|
||||
const attackerMods = await modifiersFor(tx, pid, { state: origin?.state ?? null, nowMs: due });
|
||||
const attacker: AttackerInput = { units, modifiers: attackerMods, versorgungsmangel: origin?.state.versorgungsmangel ?? false };
|
||||
let survivors = units;
|
||||
let destroyed = true;
|
||||
let battle: unknown = null;
|
||||
let seed: number | null = null;
|
||||
let defenderLeft: Counts = {};
|
||||
if (Object.keys(defenderUnits).length > 0) {
|
||||
seed = randomSeed();
|
||||
const defender: DefenderInput = field.ownerId !== null
|
||||
? { units: defenderUnits, defenses: {}, modifiers: await modifiersFor(tx, field.ownerId, { nowMs: due }) }
|
||||
: guardDefender(defenderUnits);
|
||||
const res = resolveBattle(attacker, defender, balance, seed, battleWeather(field.col, field.row, due));
|
||||
if (!res.ok) throw new Error(`battle: ${res.code}`);
|
||||
const s = strandTroops(res.report, balance);
|
||||
destroyed = s.destroyed;
|
||||
survivors = activeUnits(s.report.attacker.final);
|
||||
defenderLeft = activeUnits(s.report.defender.final);
|
||||
battle = { ...s.report, loot: {} };
|
||||
await wreckAt(tx, field, s.report.wreck, due);
|
||||
}
|
||||
const prevOwner = field.ownerId;
|
||||
let outcome: "captured" | "cleared" | "held" | "limit" = "held";
|
||||
if (destroyed) {
|
||||
if (prevOwner !== null) await endGarrison(tx, field.missionId, {}, due);
|
||||
const split = splitGarrison(survivors, !!(plan as { stayAll?: boolean }).stayAll, balance);
|
||||
const limit = origin ? maxFieldsOf(origin.state) : 0;
|
||||
if (split && origin && (await ownedBy(tx, pid)).length < limit) {
|
||||
await tx.update(tables.resourceField).set({
|
||||
ownerId: pid, baseId: origin.id, missionId: m.id, guard: {}, guardAt: null, capturedAt: new Date(due), lastTickAt: new Date(due),
|
||||
}).where(eq(tables.resourceField.id, field.id));
|
||||
await stationGarrison(tx, m, plan, split.garrison, split.rest, due);
|
||||
await recordAchievement(tx, pid, "felder", 1, { atMs: due }); // Erfolg „Landnahme“
|
||||
outcome = "captured";
|
||||
} else {
|
||||
await releaseField(tx, field, due, null);
|
||||
outcome = split ? "limit" : "cleared";
|
||||
}
|
||||
} else if (prevOwner !== null) {
|
||||
await tx.update(tables.mission).set({ returning: defenderLeft }).where(eq(tables.mission.id, field.missionId!));
|
||||
} else {
|
||||
await tx.update(tables.resourceField).set({ guard: defenderLeft }).where(eq(tables.resourceField.id, field.id));
|
||||
}
|
||||
const attackerName = await playerName(tx, pid);
|
||||
const title = outcome === "captured" ? `${name} besetzt` : outcome === "held" ? `Angriff auf ${name} abgewiesen`
|
||||
: outcome === "limit" ? `${name} freigekämpft – Höchstzahl Felder erreicht` : `${name} freigekämpft – zu schwach für eine Besatzung`;
|
||||
const reportId = await storeNavalReport(tx, {
|
||||
kind: "feld", title, attackerPlayerId: pid, defenderPlayerId: prevOwner, attackerBaseId: m.baseId, defenderBaseId: field.baseId,
|
||||
winner: destroyed ? "attacker" : "defender", seed, atMs: due,
|
||||
report: {
|
||||
field: { id: field.id, kind: field.kind, tier: field.tier, outcome, owner: ownerName },
|
||||
...(battle ? { battle, attackerName, defenderName: ownerName ?? "Kartell-Wache", targetName: name, attacker } : {}),
|
||||
},
|
||||
});
|
||||
if (outcome === "captured") {
|
||||
await tx.update(tables.mission).set({ reportId }).where(eq(tables.mission.id, m.id));
|
||||
} else {
|
||||
await sendHome(tx, m, plan, survivors, {}, reportId, due);
|
||||
}
|
||||
push.push(pushNotice(pid, "report", title, outcome === "captured" ? "Deine Besatzung hält das Feld." : "Der Verband kehrt heim.", "berichte"));
|
||||
if (prevOwner !== null) {
|
||||
const lost = destroyed;
|
||||
await systemMessage(tx, notify, [prevOwner], lost ? `${name} verloren` : `${name} gehalten`,
|
||||
lost ? `${attackerName} hat deine Besatzung auf ${name} geschlagen.${outcome === "captured" ? " Das Feld gehört jetzt ihm." : " Das Feld ist wieder neutral."}`
|
||||
: `Deine Besatzung auf ${name} hat den Angriff von ${attackerName} abgewiesen.`);
|
||||
push.push(pushNotice(prevOwner, "attack", lost ? `${name} verloren` : `${name} gehalten`, `Angreifer: ${attackerName}.`, "berichte"));
|
||||
notify.push([[prevOwner], "reports"], [[prevOwner], "missions"], [[prevOwner], "base"]);
|
||||
}
|
||||
notify.push([null, "map"], [[pid], "reports"]);
|
||||
}
|
||||
|
||||
/** Besatzung zurückrufen: Feld wird neutral, angefangener Ertrag geht noch als Konvoi heim. Codes: no_field. */
|
||||
export function fieldRecall(engine: Engine, playerId: number, key: string, fieldId: number) {
|
||||
return runCommand<{ ok: true; returnAtMs: number }>(engine, playerId, key, "fieldRecall", async (ctx) => {
|
||||
const field = await fieldById(ctx.tx, fieldId, true); // Reihenfolge: Feld vor Besatzung
|
||||
if (!field || field.ownerId !== playerId) throw new GameError("no_field");
|
||||
await settleField(ctx.tx, field, ctx.nowMs, ctx.notify);
|
||||
const [m] = field.missionId !== null ? await ctx.tx.select().from(tables.mission).where(eq(tables.mission.id, field.missionId)).for("update") : [];
|
||||
let returnAtMs = ctx.nowMs;
|
||||
if (m && m.status === "stationed") {
|
||||
const plan = m.plan as Mission;
|
||||
returnAtMs = ctx.nowMs + Math.max(0, plan.arriveAtMs - plan.departAtMs);
|
||||
await endGarrison(ctx.tx, m.id, (m.returning as Counts | null) ?? {}, ctx.nowMs);
|
||||
}
|
||||
await releaseField(ctx.tx, field, ctx.nowMs, null);
|
||||
ctx.notify.push([[playerId], "missions"], [[playerId], "base"], [null, "map"]);
|
||||
return { ok: true as const, returnAtMs };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
// Felder: Ablauf (docs/REGELN-FELDER.md). Globales field_tick alle deliveryHours: Ertrag je besetztem Feld (Rang,
|
||||
// Zonenbonus) als Konvoi zum Heimathafen (abfangbar, Blockade hält zurück), Unterhalt in Proviant, Allianzpunkte,
|
||||
// Würfel für Kartellangriffe, neue Wachen und Felder. field_delivery: Konvoi läuft ein. field_raid: Kartell greift an.
|
||||
import { and, eq, isNull, lte, sql } from "drizzle-orm";
|
||||
import {
|
||||
activeUnits, blockadeOf, cartelFieldRaid, deliverCargo, fieldUpkeep, fieldYield, resolveBattle, settle, strandTroops,
|
||||
type Counts,
|
||||
} from "@tidefront/game-core";
|
||||
import { hexDistanceKm } from "@tidefront/world";
|
||||
import { tables, type Db, type Tx } from "@tidefront/db";
|
||||
import { balance, type NoticeJob } from "./context.ts";
|
||||
import type { HandlerResult } from "./events.ts";
|
||||
import { lockBase, lockBases, randomSeed, saveBase, scheduleEvent } from "./store.ts";
|
||||
import { modifiersFor, modsOf } from "./modifiers.ts";
|
||||
import { battleWeather } from "./weather.ts";
|
||||
import { systemMessage } from "./alliance-core.ts";
|
||||
import { runningSeasonRow } from "./world-events.ts";
|
||||
import { activeBlockade, createConvoy } from "./naval.ts";
|
||||
import { pushNotice, storeNavalReport, type Notes } from "./naval-common.ts";
|
||||
import { HOUR_MS, allianceMap, fieldById, fieldName, ownedBy, rules, spawnFields, zonesOf, type FieldRow } from "./fields-core.ts";
|
||||
import { endGarrison, releaseField } from "./fields-missions.ts";
|
||||
|
||||
const none = (): HandlerResult => ({ notify: [] });
|
||||
|
||||
/**
|
||||
* Ertrag seit lastTickAt abrechnen: Unterhalt vom Heimathafen (Proviant, höchstens der Bestand), Ertrag als Konvoi
|
||||
* (Ankunft nach Fahrzeit mit convoySpeedKmh). Rang und Zone werden hier neu bestimmt. Sperrt den Heimathafen.
|
||||
*/
|
||||
export async function settleField(tx: Tx, f: FieldRow, due: number, notify: Notes, ctx?: { rank: number; zone: boolean }): Promise<void> {
|
||||
const r = rules();
|
||||
if (!r || f.ownerId === null || f.baseId === null || !f.lastTickAt) return;
|
||||
const hours = (due - f.lastTickAt.getTime()) / HOUR_MS;
|
||||
if (!(hours > 0)) return;
|
||||
let rank = ctx?.rank;
|
||||
let zone = ctx?.zone;
|
||||
if (rank === undefined || zone === undefined) {
|
||||
rank = (await ownedBy(tx, f.ownerId)).findIndex((x) => x.id === f.id);
|
||||
const all = (await tx.select().from(tables.resourceField)) as FieldRow[];
|
||||
zone = !!(await zonesOf(tx, all)).get(f.id)?.bonus;
|
||||
}
|
||||
const b = await lockBase(tx, f.baseId);
|
||||
await tx.update(tables.resourceField).set({ lastTickAt: new Date(due) }).where(eq(tables.resourceField.id, f.id));
|
||||
if (!b) return;
|
||||
const mods = await modsOf(tx, b, due);
|
||||
const state = settle(b.state, due, balance, mods);
|
||||
const upkeep = fieldUpkeep(f.tier, hours, balance);
|
||||
state.resources.proviant = Math.max(0, (state.resources.proviant ?? 0) - upkeep);
|
||||
await saveBase(tx, b.id, state);
|
||||
const cargo = fieldYield(f.kind, f.tier, hours, Math.max(0, rank), zone, balance);
|
||||
if (Object.keys(cargo).length > 0) {
|
||||
const arrive = due + Math.ceil((hexDistanceKm(f, b) / r.convoySpeedKmh) * HOUR_MS);
|
||||
const convoyId = await createConvoy(tx, {
|
||||
kind: "feld", senderId: null, recipientId: f.ownerId, recipientBaseId: b.id, from: f, to: b, cargo, departMs: due, arriveMs: arrive,
|
||||
});
|
||||
await scheduleEvent(tx, "field_delivery", arrive, { convoyId }, b.id);
|
||||
}
|
||||
notify.push([[f.ownerId], "base"], [[f.ownerId], "market"]);
|
||||
}
|
||||
|
||||
/** game_event field_tick: Lieferzyklus aller besetzten Felder. */
|
||||
async function fieldTick(tx: Tx, due: number): Promise<HandlerResult> {
|
||||
const r = rules();
|
||||
if (!r) return none();
|
||||
const notify: Notes = [[null, "map"]];
|
||||
const push: NoticeJob[] = [];
|
||||
await scheduleEvent(tx, "field_tick", due + r.deliveryHours * HOUR_MS, {}, null);
|
||||
await spawnFields(tx, due);
|
||||
// Neue Kartell-Wachen auf neutralen Feldern.
|
||||
const due0 = await tx.select().from(tables.resourceField)
|
||||
.where(and(isNull(tables.resourceField.ownerId), lte(tables.resourceField.guardAt, new Date(due)))) as FieldRow[];
|
||||
for (const f of due0) {
|
||||
await tx.update(tables.resourceField).set({ guard: { ...(r.guard[f.tier - 1] ?? {}) }, guardAt: null }).where(eq(tables.resourceField.id, f.id));
|
||||
}
|
||||
const all = (await tx.select().from(tables.resourceField).orderBy(tables.resourceField.id).for("update")) as FieldRow[];
|
||||
const owned = all.filter((f) => f.ownerId !== null);
|
||||
if (owned.length === 0) return { notify };
|
||||
const zones = await zonesOf(tx, all);
|
||||
await lockBases(tx, owned.map((f) => f.baseId!).filter((id) => id !== null));
|
||||
const am = await allianceMap(tx);
|
||||
const byOwner = new Map<number, FieldRow[]>();
|
||||
for (const f of owned) byOwner.set(f.ownerId!, [...(byOwner.get(f.ownerId!) ?? []), f]);
|
||||
const points = new Map<number, number>();
|
||||
for (const list of byOwner.values()) {
|
||||
list.sort((a, b) => (a.capturedAt?.getTime() ?? 0) - (b.capturedAt?.getTime() ?? 0) || a.id - b.id);
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const f = list[i];
|
||||
const hours = f.lastTickAt ? (due - f.lastTickAt.getTime()) / HOUR_MS : 0;
|
||||
await settleField(tx, f, due, notify, { rank: i, zone: !!zones.get(f.id)?.bonus });
|
||||
const a = am.get(f.ownerId!);
|
||||
if (a !== undefined && hours > 0) points.set(a, (points.get(a) ?? 0) + (r.alliancePointsPerFieldDay * hours) / 24);
|
||||
const raid = cartelFieldRaid(f.tier, randomSeed(), balance);
|
||||
if (raid) {
|
||||
const at = due + r.cartelRaidLeadMinutes * 60000;
|
||||
await scheduleEvent(tx, "field_raid", at, { fieldId: f.id, ownerId: f.ownerId, units: raid }, null);
|
||||
push.push(pushNotice(f.ownerId!, "attack", `Kartell hält auf ${fieldName(f)} zu`, `Ankunft in etwa ${r.cartelRaidLeadMinutes} Minuten. Deine Besatzung verteidigt.`));
|
||||
await systemMessage(tx, notify, [f.ownerId!], `Kartell hält auf ${fieldName(f)} zu`, `Ein Kartellverband (${raid.schnellboot ?? 0} Schnellboote) greift in etwa ${r.cartelRaidLeadMinutes} Minuten dein Feld an.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const [allianceId, p] of points) {
|
||||
await tx.insert(tables.fieldScore).values({ allianceId, points: p })
|
||||
.onConflictDoUpdate({ target: tables.fieldScore.allianceId, set: { points: sql`${tables.fieldScore.points} + ${p}` } });
|
||||
}
|
||||
return { notify, push };
|
||||
}
|
||||
|
||||
/** game_event field_delivery: Ertragskonvoi läuft ein (Blockade hält ihn zurück). */
|
||||
async function fieldDelivery(tx: Tx, payload: Record<string, unknown>, due: number): Promise<HandlerResult> {
|
||||
const [c] = await tx.select().from(tables.convoy).where(eq(tables.convoy.id, Number(payload.convoyId))).for("update");
|
||||
if (!c || c.status !== "underway") return none();
|
||||
const bb = blockadeOf(balance);
|
||||
const block = bb ? await activeBlockade(tx, { baseId: c.recipientBaseId }, due) : null;
|
||||
if (block && bb) {
|
||||
const next = Math.max(due + 1000, Math.min(block.endsAt.getTime(), due + bb.deliveryHoldMinutes * 60000));
|
||||
await tx.update(tables.convoy).set({ arriveAt: new Date(next) }).where(eq(tables.convoy.id, c.id));
|
||||
await scheduleEvent(tx, "field_delivery", next, { convoyId: c.id }, c.recipientBaseId);
|
||||
return none();
|
||||
}
|
||||
await tx.update(tables.convoy).set({ status: "arrived" }).where(eq(tables.convoy.id, c.id));
|
||||
const b = await lockBase(tx, c.recipientBaseId);
|
||||
if (b) await saveBase(tx, b.id, deliverCargo(b.state, c.cargo as Counts, due, balance, await modsOf(tx, b, due)));
|
||||
return { notify: [[[c.recipientId], "base"], [[c.recipientId], "market"]] };
|
||||
}
|
||||
|
||||
/** game_event field_raid: Kartellverband gegen die Besatzung. Unterliegt sie, hält das Kartell das Feld (neutral). */
|
||||
async function fieldRaid(tx: Tx, payload: Record<string, unknown>, due: number): Promise<HandlerResult> {
|
||||
const f = await fieldById(tx, Number(payload.fieldId), true);
|
||||
if (!f || f.ownerId === null || f.ownerId !== Number(payload.ownerId) || f.missionId === null) return none();
|
||||
const [m] = await tx.select().from(tables.mission).where(eq(tables.mission.id, f.missionId)).for("update");
|
||||
if (!m || m.status !== "stationed") return none();
|
||||
const owner = f.ownerId;
|
||||
const units = activeUnits(payload.units as Counts);
|
||||
const garrison = activeUnits((m.returning as Counts | null) ?? {});
|
||||
const seed = randomSeed();
|
||||
const res = resolveBattle({ units }, { units: garrison, defenses: {}, modifiers: await modifiersFor(tx, owner, { nowMs: due }) }, balance, seed, battleWeather(f.col, f.row, due));
|
||||
if (!res.ok) throw new Error(`battle: ${res.code}`);
|
||||
const { report, destroyed } = strandTroops(res.report, balance);
|
||||
const name = fieldName(f);
|
||||
const notify: Notes = [[null, "map"], [[owner], "reports"], [[owner], "missions"]];
|
||||
if (destroyed) {
|
||||
await endGarrison(tx, m.id, {}, due);
|
||||
await releaseField(tx, f, due, { ...(rules()!.guard[f.tier - 1] ?? {}) });
|
||||
} else {
|
||||
await tx.update(tables.mission).set({ returning: activeUnits(report.defender.final) }).where(eq(tables.mission.id, m.id));
|
||||
}
|
||||
if ((report.wreck.stahl ?? 0) + (report.wreck.elektronik ?? 0) > 0) {
|
||||
await tx.insert(tables.wreck).values({ col: f.col, row: f.row, stahl: report.wreck.stahl ?? 0, elektronik: report.wreck.elektronik ?? 0, createdAt: new Date(due) });
|
||||
}
|
||||
const title = destroyed ? `${name} an das Kartell verloren` : `Kartell vor ${name} abgewehrt`;
|
||||
await storeNavalReport(tx, {
|
||||
kind: "feld", title, attackerPlayerId: null, defenderPlayerId: owner, defenderBaseId: f.baseId, winner: destroyed ? "attacker" : "defender", seed, atMs: due,
|
||||
report: { field: { id: f.id, kind: f.kind, tier: f.tier, outcome: destroyed ? "cartel" : "held" }, battle: { ...report, loot: {} }, attackerName: "Freibeuter-Kartell", defenderName: "Besatzung", targetName: name, attacker: { units } },
|
||||
});
|
||||
await systemMessage(tx, notify, [owner], title, destroyed ? `Das Kartell hat deine Besatzung auf ${name} geschlagen. Das Feld ist wieder neutral.` : `Deine Besatzung auf ${name} hat den Kartellverband zurückgeschlagen.`);
|
||||
return { notify, push: [pushNotice(owner, "attack", title, destroyed ? "Das Feld ist wieder neutral." : "Das Feld bleibt deins.", "berichte")] };
|
||||
}
|
||||
|
||||
export const FIELD_HANDLERS: Record<string, (tx: Tx, ev: { payload: Record<string, unknown> }, due: number) => Promise<HandlerResult>> = {
|
||||
field_tick: (tx, _ev, due) => fieldTick(tx, due),
|
||||
field_delivery: (tx, ev, due) => fieldDelivery(tx, ev.payload, due),
|
||||
field_raid: (tx, ev, due) => fieldRaid(tx, ev.payload, due),
|
||||
};
|
||||
|
||||
/** Worker (alle 10 Minuten, auch nach Saisonwechsel): Felder anlegen und field_tick planen, falls keines ansteht. */
|
||||
export async function ensureFieldPlanner(db: Db, nowMs: number): Promise<number | null> {
|
||||
const r = rules();
|
||||
if (!r) return null;
|
||||
return db.transaction(async (tx) => {
|
||||
await tx.execute(sql`select pg_advisory_xact_lock(7340013)`);
|
||||
if (!(await runningSeasonRow(tx))) return null;
|
||||
await spawnFields(tx, nowMs);
|
||||
const [pending] = await tx.select({ id: tables.gameEvent.id }).from(tables.gameEvent)
|
||||
.where(and(eq(tables.gameEvent.type, "field_tick"), eq(tables.gameEvent.status, "pending"))).limit(1);
|
||||
if (pending) return null;
|
||||
const at = nowMs + r.deliveryHours * HOUR_MS;
|
||||
await scheduleEvent(tx, "field_tick", at, {}, null);
|
||||
return at;
|
||||
});
|
||||
}
|
||||
|
||||
/** Saisonende: Felder und Feldpunkte verfallen (geplante Ereignisse löscht season.ts). */
|
||||
export async function clearFields(tx: Tx): Promise<void> {
|
||||
await tx.delete(tables.fieldScore);
|
||||
await tx.delete(tables.resourceField);
|
||||
}
|
||||
|
||||
/** Allianzwertung: Feldpunkte je Allianz (gerundet). */
|
||||
export async function fieldPoints(tx: Tx | Db): Promise<Map<number, number>> {
|
||||
const rows = await tx.select().from(tables.fieldScore);
|
||||
return new Map(rows.map((r) => [r.allianceId, Math.round(r.points)]));
|
||||
}
|
||||
@@ -44,6 +44,8 @@ import { admiralsAfterBattle, defenseAdmiral, missionAdmiral } from "./admirals-
|
||||
// Allianz-Ops: Stationierung (Ankunft, stationierte Verbündete verteidigen mit)
|
||||
import { STATION_TYPE, settleGuests, stationArrive, stationedGuests, withGuests } from "./alliance-ops-station.ts";
|
||||
import { holdDelivery, NAVAL_HANDLERS, navalArrive } from "./naval.ts"; // See: Minen/Blockade/Konvoi
|
||||
import { fieldArrive } from "./fields-missions.ts"; // Felder: Aufklärung/Besetzen
|
||||
import { FIELD_HANDLERS } from "./fields-run.ts"; // Felder: field_tick, field_delivery, field_raid
|
||||
|
||||
const HOUR_MS = 3600000;
|
||||
const none = (): HandlerResult => ({ notify: [] });
|
||||
@@ -174,6 +176,7 @@ const missionArrive: Handler = async (tx, ev, due) => {
|
||||
if (naval.done) return { notify: [...notify, [[m.playerId!], "reports"], [[m.playerId!], "base"]], push };
|
||||
plan = naval.plan;
|
||||
const origin = await readBase(tx, m.baseId!);
|
||||
if (m.targetKind === "field") { await fieldArrive(tx, m, plan, origin, due, notify, push); return { notify: [...notify, [[m.playerId!], "base"]], push }; } // Felder
|
||||
let returning: Counts = { ...plan.units };
|
||||
let cargoHome: ResourceMap = {};
|
||||
let reportId: number | null = null;
|
||||
@@ -440,6 +443,7 @@ export const HANDLERS: Record<string, Handler> = {
|
||||
attack_warning: attackWarning,
|
||||
...WORLD_EVENT_HANDLERS,
|
||||
...NAVAL_HANDLERS, // See: Minen/Blockade/Konvoi (blockade_end, convoy_raid)
|
||||
...FIELD_HANDLERS, // Felder
|
||||
pact_expire: (tx, _ev, due) => import("./alliance-core.ts").then(async (m) => {
|
||||
const notify: HandlerResult["notify"] = [];
|
||||
await m.purgeExpired(tx, due, notify);
|
||||
|
||||
@@ -66,3 +66,7 @@ export { stationRelease, STATION_TYPE } from "./alliance-ops-station.ts";
|
||||
export { allianceRaidsView } from "./alliance-ops-view.ts";
|
||||
// See: Minen, Blockade und Konvois
|
||||
export { navalView, navalRouteMines, liftBlockade, clearNaval, NAVAL_TYPES } from "./naval.ts";
|
||||
// Felder: Rohstofffelder einnehmen
|
||||
export { fieldsView, spawnFields, FIELD_KIND_TEXT } from "./fields-core.ts";
|
||||
export { fieldRecall } from "./fields-missions.ts";
|
||||
export { ensureFieldPlanner, clearFields } from "./fields-run.ts";
|
||||
@@ -66,7 +66,7 @@ const route = (c: ConvoyRow) => buildRoute([hexCenter(c.fromCol, c.fromRow), hex
|
||||
export async function createConvoy(
|
||||
tx: Tx,
|
||||
v: {
|
||||
kind: "handel" | "transport"; deliveryId?: string; missionId?: number; senderId: number | null; recipientId: number; recipientBaseId: number;
|
||||
kind: "handel" | "transport" | "feld"; deliveryId?: string; missionId?: number; senderId: number | null; recipientId: number; recipientBaseId: number; // Felder: "feld"
|
||||
from: { col: number; row: number }; to: { col: number; row: number }; cargo: ResourceMap; escort?: Counts; departMs: number; arriveMs: number;
|
||||
},
|
||||
): Promise<number> {
|
||||
|
||||
@@ -27,6 +27,8 @@ export async function allianceStandings(db: DbOrTx, totals: Map<number, number>)
|
||||
a.playerIds.push(r.playerId);
|
||||
by.set(r.allianceId, a);
|
||||
}
|
||||
const fp = await (await import("./fields-run.ts")).fieldPoints(db); // Felder: Feldpunkte der Allianzen
|
||||
for (const a of by.values()) a.total += fp.get(a.allianceId) ?? 0;
|
||||
const list = [...by.values()].sort((x, y) => y.total - x.total || x.name.localeCompare(y.name, "de"));
|
||||
list.forEach((a, i) => { a.rank = i > 0 && a.total === list[i - 1].total ? list[i - 1].rank : i + 1; });
|
||||
return list;
|
||||
|
||||
@@ -161,6 +161,7 @@ export const seasonEnd: Handler = async (tx, ev, due) => {
|
||||
await resetChallenges(tx);
|
||||
await clearWorldEvents(tx);
|
||||
await (await import("./naval.ts")).clearNaval(tx); // See: Minen/Blockade/Konvoi verfallen
|
||||
await (await import("./fields-run.ts")).clearFields(tx); // Felder: Besitz und Feldpunkte verfallen
|
||||
// Marktnachrichten verfallen; die Börse steht wieder auf dem Grundrichtwert.
|
||||
await clearMarketNews(tx);
|
||||
await tx.update(tables.nest).set({ defeatedAt: null });
|
||||
|
||||
@@ -52,6 +52,7 @@ import { admiralPreviewMods } from "./admirals-core.ts"; // Admirale
|
||||
import { STATION_TYPE, stationPreview, stationedView } from "./alliance-ops-station.ts";
|
||||
import { sharedReportIds } from "./alliance-ops-view.ts";
|
||||
import { isNavalInput, previewNaval } from "./naval.ts"; // See: Minen/Blockade/Konvoi
|
||||
import { previewField } from "./fields-missions.ts"; // Felder
|
||||
|
||||
/**
|
||||
* Ist ein feindlicher Verband auf dem Anmarsch und schon vom Radar erfasst? (Radar mit `mods`, Tarnung je Verband;
|
||||
@@ -251,11 +252,12 @@ export async function mapView(engine: Engine, playerId: number) {
|
||||
export async function missionPreview(
|
||||
engine: Engine,
|
||||
playerId: number,
|
||||
input: { type: string; units: Counts; col: number; row: number; cargo?: ResourceMap; eventId?: number; admiralId?: number; blockadeId?: number; convoyId?: number; holdHours?: number },
|
||||
input: { type: string; units: Counts; col: number; row: number; cargo?: ResourceMap; eventId?: number; admiralId?: number; blockadeId?: number; convoyId?: number; holdHours?: number; fieldId?: number; stayAll?: boolean },
|
||||
) {
|
||||
const nowMs = Date.now();
|
||||
const own = await baseOfPlayer(engine.db, playerId);
|
||||
if (!own) return { ok: false as const, code: "no_base" };
|
||||
if (input.fieldId !== undefined) return previewField(engine.db, playerId, own, { ...input, fieldId: input.fieldId }, nowMs); // Felder
|
||||
if (input.eventId !== undefined) return previewAgainstEvent(engine.db, playerId, own, { ...input, eventId: input.eventId }, nowMs);
|
||||
if (input.type === STATION_TYPE) return stationPreview(engine.db, playerId, own, input, nowMs); // Allianz-Ops
|
||||
if (isNavalInput(input)) return previewNaval(engine.db, playerId, own, input, nowMs); // See: Minen/Blockade/Konvoi
|
||||
|
||||
Reference in new issue
Block a user