mirror of
https://github.com/db9979/tidefront.git
synced 2026-12-06 21:04:12 +01:00
Lücken im Regelkern geschlossen: Wetter bei Weltereignissen, Radar bleibt erkannt, Spione zurück, Belagerung und Admin-Statistik mit Modifikatoren, Allianzwertung im Saisonergebnis, Tagesbefehle zu Strom, Wetter und Nachrichtendienst
- Weltereignisse: Planung/Vorschau mit Routenwetter und Modifikatoren, Kämpfe (See und Hafenangriff der Großflotte) mit Wetter am Kampfort - Radar: Erkennungszeitpunkt im Missionsplan (plan.detectedAtMs); attack_warning prüft das Radar zum Warnzeitpunkt und plant sonst neu - Heimkehr von Spionage-Aufträgen: Meldung „Spione zurück“ mit Art, Ziel und Ergebnis - Belagerungsabzug und Admin-Statistik über modsOf wie die normale Produktion - Neue Tabelle season_alliance_result (Schema, ohne Migration), Ruhmeshalle und Saisonnachricht zeigen die Allianzwertung - Tagesbefehle speicherwerk, stromspeicher, sturmfahrt, erkundung - Regeltexte ergänzt, Tests in packages/engine/test/luecken.test.ts
This commit is contained in:
1 parent
fdb1863eab
commit
b9209ca3d9
20 files changed
+669
-41
No files matched your search
@@ -29,7 +29,7 @@ export function timelineItems(base: BaseData, nowMs: number, opts: { seasonEndMs
|
||||
}
|
||||
for (const m of base.missions) {
|
||||
if (m.status === "outbound") out.push({ key: `ma:${m.id}`, atMs: m.arriveAtMs, icon: m.type, text: `${label(m.type)}: Ankunft Feld ${m.target.col}/${m.target.row}` });
|
||||
out.push({ key: `mr:${m.id}`, atMs: m.returnAtMs, icon: m.type, text: `${label(m.type)}: Verband zurück` });
|
||||
out.push({ key: `mr:${m.id}`, atMs: m.returnAtMs, icon: m.type, text: m.type === "spionage" ? "Spione zurück" : `${label(m.type)}: Verband zurück` });
|
||||
}
|
||||
for (const i of base.incoming) {
|
||||
const attack = i.type !== "transport";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Ruhmeshalle: vergangene Saisons mit Podium, Kategoriebesten und eigenem Ergebnis.
|
||||
// Ruhmeshalle: vergangene Saisons mit Podium, Kategoriebesten, Allianzwertung und eigenem Ergebnis.
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { trpc } from "../lib/trpc.ts";
|
||||
import { fmtNum } from "../lib/names.ts";
|
||||
@@ -46,6 +46,7 @@ export function HallOfFame() {
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
{s.alliances.length > 0 && <SeasonAlliances alliances={s.alliances} />}
|
||||
{s.own && (
|
||||
<div className="mt-2 pt-2 border-t border-navy-600 text-xs">
|
||||
<span className="text-slate-400">Du: </span>
|
||||
@@ -63,3 +64,24 @@ export function HallOfFame() {
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
type AllianceRow = { rank: number; name: string; tag: string; members: number; total: number; own: boolean };
|
||||
|
||||
/** Allianzwertung einer Saison: die ersten drei und die eigene Allianz (Summe der Mitgliederpunkte). */
|
||||
function SeasonAlliances({ alliances }: { alliances: AllianceRow[] }) {
|
||||
const shown = alliances.filter((a, i) => i < 3 || a.own);
|
||||
return (
|
||||
<div className="mt-2 pt-2 border-t border-navy-600">
|
||||
<div className="text-[11px] text-slate-400 mb-1">Allianzwertung ({alliances.length})</div>
|
||||
<ol className="text-xs space-y-0.5">
|
||||
{shown.map((a) => (
|
||||
<li key={`${a.rank}-${a.tag}`} className={`flex items-center gap-2 ${a.own ? "text-sea-300" : ""}`}>
|
||||
<span className="w-5 text-center tabular-nums text-slate-400">{a.rank}</span>
|
||||
<span className="flex-1 truncate"><span className="mono text-ink2">[{a.tag}]</span> {a.name} <span className="text-slate-500">· {a.members}</span></span>
|
||||
<span className="font-mono tabular-nums text-slate-300">{fmtNum(a.total)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -43,4 +43,6 @@ Teil der Regeln (siehe `docs/REGELN.md`).
|
||||
Abwehr in der Kampfbilanz (Kategorie Spionage), Kampfpunkte für das Ziel in der Wertung.
|
||||
- **Unentdeckt:** Erfolg, das Ziel merkt nichts. Bei einer Sabotage sieht es nur die Folgen (Bericht `sabotage` ohne
|
||||
Absender, Hinweis „sabotiert bis …“ im Hafen). Die Spione kehren heim (`mission_return`); der Absender erhält den
|
||||
Spionagebericht.
|
||||
Spionagebericht. Bei der Heimkehr meldet sich „Spione zurück“ mit Art, Ziel und Ergebnis (gelungen oder
|
||||
abgebrochen), nicht das allgemeine „Verband zurück“. Gelungenes Erkunden und Kartell-Aufklärung zählen für den
|
||||
Tagesbefehl „Erfolgreiche Erkundung“.
|
||||
@@ -66,6 +66,8 @@ und `research_complete` bleiben unverändert); spätere Änderungen am Hafen ver
|
||||
- **Kampf:** Wetter am Kampfort zum Kampfzeitpunkt. Aller Schaden von Flugzeugen (Luftkampf, Luftschlag) beider Seiten mal
|
||||
`1 − airStormPenalty * Sturmanteil` (0,6); der Luftschlag der Bomber zusätzlich mal `1 − cloudStrikePenalty * Bewölkung`
|
||||
(0,3). Flak und Schiffe sind nicht betroffen. Der Bericht enthält das Wetter.
|
||||
- **Weltereignisse:** Missionen gegen Großflotte, Schatzschiff und Belagerungsring planen mit dem Wetter der Route
|
||||
(Vorschau und Plan wie oben); ihre Kämpfe und die Hafenangriffe der Großflotte rechnen mit dem Wetter am Kampfort.
|
||||
- **Nebel und Radar:** Vorwarnzeit mal `1 − fogRadarMax * Nebel` am Hafen (bis −30 %), als Modifikator-Quelle „Wetter“
|
||||
(auf ganze Prozent gerundet, nur mit Radarstation).
|
||||
- **Nebel und Aufklärung:** Ab Nebel `fogScoutFrom` (0,35) am Ziel ist das Lagebild unsicher (`uncertain`): Bestände auf
|
||||
|
||||
+16
-4
@@ -91,6 +91,9 @@ Rückruf:
|
||||
- Radarstation Stufe L ≥ 1: Vorwarnzeit `warningMinutesBase + warningMinutesPerLevel * L` Minuten, ohne Radar 0; seit v1.6 mal Stromanteil des Radars und Nebelfaktor.
|
||||
- Ein anrückender Angriff gilt als erkannt, sobald seine Ankunft höchstens die Vorwarnzeit entfernt ist.
|
||||
Erst dann sieht der Verteidiger ihn, und erst dann greift an der Börse die Sperre `under_attack`.
|
||||
- **Einmal erkannt bleibt erkannt:** Der Erkennungszeitpunkt wird an der Mission gemerkt. Fällt das Radar danach aus
|
||||
(Strommangel, Sabotage, Nebel), bleibt der Angriff sichtbar. Die Push-Warnung „Angriff erkannt“ prüft das Radar zum
|
||||
Zeitpunkt der Warnung; erfasst es den Verband noch nicht, wird spätestens alle 15 Minuten neu geprüft (bis zur Ankunft).
|
||||
|
||||
## Abbruch
|
||||
|
||||
@@ -226,7 +229,8 @@ Zeitlich begrenzte Ereignisse auf der Karte, die alle Spieler betreffen und Zusa
|
||||
- **Belagerung:** Ring aus Schnellbooten (`shareOfDefense`, `minSchnellboote`, Bezug: der belagerte Hafen) für
|
||||
`durationHours`. Wirkung: keine Börsenkäufe (`siege`; Lieferungen, die schon unterwegs sind, kommen an) und
|
||||
`productionPenalty` der Gebäudeproduktion: alle `tickMinutes` wird dieser Anteil der Gebäudeproduktion seit dem
|
||||
letzten Abzug abgezogen (nicht bei vollem Lager, nie unter 0), zuletzt beim Ende bzw. Bruch. Der Besitzer kann den
|
||||
letzten Abzug abgezogen (nicht bei vollem Lager, nie unter 0), zuletzt beim Ende bzw. Bruch. Grundlage ist die
|
||||
Gebäudeproduktion mit allen Modifikatoren (Forschung, Sabotage, Strom, Wetter, Ereignisse) wie im Hafen. Der Besitzer kann den
|
||||
Ring nicht selbst angreifen (`own_siege`); andere Spieler brechen ihn, indem sie den Verband vernichten.
|
||||
- **Beute für Schaden** (Großflotte, Belagerung): Beutepool `lootPool * Stärkefaktor` (Großflotte: plus ihre Beute aus
|
||||
Hafenangriffen). Je Angriff erhält der Angreifer `Pool * vernichtete Lebenspunkte / Anfangs-Lebenspunkte`, höchstens
|
||||
@@ -311,6 +315,9 @@ Werte unter `market.news` (seit v1.5), Kern `packages/game-core/src/market/news.
|
||||
- Am Saisonende: Gold, Silber und Bronze für Rang 1 bis 3 (mit Punkten), je Kategorie eine Auszeichnung für den Besten
|
||||
(für Befehle: „Pflichtbewusstester Kapitän“). Der Endstand hält alle fünf Kategorien fest.
|
||||
Jeder Spieler erhält eine Systemnachricht mit Platz und Auszeichnungen.
|
||||
- Allianzwertung zum Saisonende: je Allianz die Summe der Gesamtpunkte ihrer Mitglieder zu diesem Zeitpunkt, Rang
|
||||
nach Punkten (Gleichstand teilt den Rang). Festgehalten in `season_alliance_result` (Name, Kürzel, Mitglieder, Punkte),
|
||||
angezeigt in der Ruhmeshalle; die Systemnachricht nennt die stärkste und die eigene Allianz.
|
||||
- Danach wird die Welt zurückgesetzt: Stützpunkte, Missionen, Lieferungen, Wracks, Kampfberichte und Kredite verfallen,
|
||||
Nester sind wieder besetzt, die Börse steht auf Richtwert, Tagesbefehle und Serien verfallen. Konten, Nachrichten und die Ruhmeshalle bleiben.
|
||||
Jeder Spieler wählt einen neuen Hafen und erhält erneut Anfängerschutz.
|
||||
@@ -344,11 +351,16 @@ Werte unter `market.news` (seit v1.5), Kern `packages/game-core/src/market/news.
|
||||
| Beute machen | m/s | Werft und Kaserne | 1.500 / 4.000 × (1 + s/4) |
|
||||
| Überfall ohne eigene Verluste gewinnen | s | Werft und Kaserne | 1 |
|
||||
| Forschung abschließen | m | Forschungsamt | 1 |
|
||||
| Speicherwerk ausbauen | m | Speicherwerk, nächste Stufe ≤ 12 h Bauzeit | Stufe + 1 |
|
||||
| Stromüberschuss halten (Speicher füllen) | l | Speicherwerk, Speicher unter dem Ziel | 60 % der Speicherkapazität, auf 10 gerundet |
|
||||
| Mission trotz Sturm erfolgreich | m/s | Werft oder Flugfeld, Wetter aktiv | 1 (Sturmanteil der Route bei Abfahrt ≥ 0,2; Aufklärung, Transport oder gewonnener Überfall) |
|
||||
| Erfolgreiche Erkundung (Nachrichtendienst) | l/m | Nachrichtendienst ab Stufe für „erkunden“, Ziel erreichbar | 1 / 2 (Erkunden oder Kartell-Aufklärung gelingt) |
|
||||
|
||||
- Fortschritt zählt nur für Geschehen am selben Spieltag (Zeitpunkt des Ereignisses) und nur nach der Vergabe:
|
||||
Ausbau, Ausbildung, Anlagen, Kampf, Aufklärung, Transport, Wrack und Beute aus den verarbeiteten Ereignissen,
|
||||
Börsenhandel (Kreditbetrag des Handels) und Bauschlange (höchste Länge) aus den Befehlen. Vorrat, Produktion,
|
||||
Forschung zählt beim Abschluss (Ereignis). Kommandozentrale und Nachrichten werden beim Abruf und beim Abholen aus dem Zustand gelesen.
|
||||
Forschung zählt beim Abschluss (Ereignis). Kommandozentrale, Speicherwerk, Stromspeicher und Nachrichten werden beim
|
||||
Abruf und beim Abholen aus dem Zustand gelesen.
|
||||
- Belohnung je Befehl: Ressourcenpaket im Wert 400 / 1.000 / 2.500 × (1 + 0,3·s) (Stahl 40 %, Treibstoff 25 %,
|
||||
Elektronik 15 %, Proviant 20 %, auf 10 gerundet; s bei der Vergabe) und 3 / 6 / 12 Punkte der Kategorie Befehle.
|
||||
Abholen ist ein Befehl mit Idempotenz-Schlüssel und gelingt genau einmal; die Ressourcen werden auch über die
|
||||
@@ -415,8 +427,8 @@ Werte unter `market.news` (seit v1.5), Kern `packages/game-core/src/market/news.
|
||||
- Allianz-Chat: höchstens 500 Zeichen je Zeile, 20 Zeilen je Minute und Spieler, sichtbar sind die letzten 100 Zeilen.
|
||||
- Wertung: Allianzpunkte = Summe der Gesamtpunkte der aktuellen Mitglieder; Rang nach Allianzpunkten, Gleichstand teilt den Rang.
|
||||
Das Kürzel steht in Rangliste und Spielerübersicht vor dem Namen.
|
||||
- Saisonende: Allianzen, Mitgliedschaften, Chat und Verträge bleiben bestehen. Allianzpunkte werden nicht in
|
||||
`season_result` festgehalten.
|
||||
- Saisonende: Allianzen, Mitgliedschaften, Chat und Verträge bleiben bestehen. Die Allianzwertung zum Saisonende wird
|
||||
in `season_alliance_result` festgehalten (siehe Wertung).
|
||||
|
||||
## Diplomatie
|
||||
|
||||
|
||||
@@ -625,3 +625,20 @@ export const bugReport = pgTable("bug_report", {
|
||||
/** E-Mail an die Verwaltung verschickt (null = nicht eingerichtet oder fehlgeschlagen). */
|
||||
mailedAt: ts("mailed_at"),
|
||||
}, (t) => [index("bug_report_player").on(t.playerId, t.createdAt), index("bug_report_status").on(t.status, t.id)]);
|
||||
|
||||
// ================================================================ Allianzwertung zum Saisonende
|
||||
// Summe der Mitgliederpunkte (season_result.total) je Allianz zum Saisonende; Name und Kürzel wie damals.
|
||||
|
||||
export const seasonAllianceResult = pgTable("season_alliance_result", {
|
||||
id: serial("id").primaryKey(),
|
||||
seasonId: integer("season_id").notNull().references(() => season.id, { onDelete: "cascade" }),
|
||||
/** null, wenn die Allianz inzwischen aufgelöst ist. */
|
||||
allianceId: integer("alliance_id").references(() => alliance.id, { onDelete: "set null" }),
|
||||
name: text("name").notNull(),
|
||||
tag: text("tag").notNull(),
|
||||
rank: integer("rank").notNull(),
|
||||
members: integer("members").notNull(),
|
||||
total: integer("total").notNull(),
|
||||
/** Spieler-IDs der Mitglieder zum Saisonende (eigene Allianz in der Ruhmeshalle). */
|
||||
playerIds: jsonb("player_ids").notNull().default([]),
|
||||
}, (t) => [uniqueIndex("season_alliance_result_alliance").on(t.seasonId, t.allianceId), index("season_alliance_result_rank").on(t.seasonId, t.rank)]);
|
||||
@@ -6,6 +6,7 @@ import { productionRates, settle, type BaseState } from "@tidefront/game-core";
|
||||
import type { Db } from "@tidefront/db";
|
||||
import { marketNewsAdmin } from "./market-news.ts";
|
||||
import { balance } from "./context.ts";
|
||||
import { modsOf } from "./modifiers.ts";
|
||||
|
||||
export const STATS_CACHE_MS = 60_000;
|
||||
/** Auffällig: Ressourcen über dem Vielfachen des Medians (ab 3 Spielern und Mindestmenge). */
|
||||
@@ -193,8 +194,10 @@ export async function adminStats(db: Db, days: StatsDays, nowMs = Date.now(), tz
|
||||
const levels = new Map(buildingIds.map((id) => [id, [] as number[]]));
|
||||
const totals: { playerId: number; name: string; total: number }[] = [];
|
||||
for (const b of bases) {
|
||||
const s = settle(b.state, nowMs, balance);
|
||||
for (const [r, v] of Object.entries(productionRates(s, balance).perHour)) add(production, r, v);
|
||||
// Produktion über die Modifikatoren wie im Stützpunkt (Forschung, Sabotage, Strom, Wetter, Ereignisse).
|
||||
const mods = await modsOf(db, { playerId: b.player_id, state: b.state }, nowMs);
|
||||
const s = settle(b.state, nowMs, balance, mods);
|
||||
for (const [r, v] of Object.entries(productionRates(s, balance, mods).perHour)) add(production, r, v);
|
||||
let total = 0;
|
||||
for (const r of balance.resources) total += s.resources[r] ?? 0;
|
||||
totals.push({ playerId: b.player_id, name: b.name, total });
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
// Reine Funktionen (keine Datenbank); die Datenbankseite steht in challenges.ts.
|
||||
import {
|
||||
mulberry32,
|
||||
powerAt,
|
||||
productionRates,
|
||||
storageCapacity,
|
||||
upgradeDurationMs,
|
||||
type BaseState,
|
||||
type Modifiers,
|
||||
type ResourceMap,
|
||||
} from "@tidefront/game-core";
|
||||
import { balance } from "./context.ts";
|
||||
@@ -89,6 +91,8 @@ export interface PoolContext {
|
||||
raidsPossible: boolean;
|
||||
/** Es gibt andere Spieler mit Hafen. */
|
||||
others: boolean;
|
||||
/** Stromspeicher (Speicherwerk): Bestand und Kapazität; fehlt = kein Speicher. */
|
||||
power?: { stored: number; capacity: number };
|
||||
}
|
||||
|
||||
export interface Spec {
|
||||
@@ -115,6 +119,17 @@ const canLand = (c: PoolContext) => lvl(c, "werft") >= 1 && lvl(c, "kaserne") >=
|
||||
const canSail = (c: PoolContext) => lvl(c, "werft") >= 1 || lvl(c, "flugfeld") >= 1;
|
||||
const one = (n: number, a: string, b: string) => (n === 1 ? a : b);
|
||||
|
||||
/** Nachrichtendienst: Erkunden möglich (Stufe für „erkunden“; Ziel ein Mitspieler oder das Kartell). */
|
||||
function canScout(c: PoolContext): boolean {
|
||||
const e = balance.espionage;
|
||||
if (!e) return false;
|
||||
const level = lvl(c, e.building);
|
||||
return level >= e.kinds.erkunden.minLevel && (c.others || level >= (e.kinds.kartell?.minLevel ?? Infinity));
|
||||
}
|
||||
|
||||
/** Ab diesem Sturmanteil der Route (0–1) gilt eine Mission als „trotz Sturm“ (Tagesbefehl sturmfahrt). */
|
||||
export const STORM_MISSION_FROM = 0.2;
|
||||
|
||||
/** Höchste Nest-Stufe, die zum Fortschritt passt (1 bis 5). */
|
||||
function nestCap(c: PoolContext): number {
|
||||
return Math.max(1, Math.min(5, 1 + Math.floor(c.stage / 3)));
|
||||
@@ -231,6 +246,35 @@ export const KINDS: Record<string, KindDef> = {
|
||||
spec: (t, c) => (t === 2 && canLand(c) ? { param: null, target: 1 } : null),
|
||||
text: () => "Gewinne einen Überfall ohne eigene Verluste",
|
||||
},
|
||||
// Strom, Wetter, Nachrichtendienst (v1.6): nur mit dem Gebäude bzw. wenn erreichbar.
|
||||
speicherwerk: {
|
||||
icon: "speicherwerk",
|
||||
spec: (t, c) => {
|
||||
const next = lvl(c, "speicherwerk") + 1;
|
||||
if (t !== 1 || next < 2 || next > balance.building.maxLevel || upgradeDurationMs("speicherwerk", next, balance) > 12 * 3600000) return null;
|
||||
return { param: null, target: next };
|
||||
},
|
||||
text: (n) => `Baue das Speicherwerk auf Stufe ${n} aus`,
|
||||
},
|
||||
stromspeicher: {
|
||||
icon: "strom",
|
||||
spec: (t, c) => {
|
||||
if (t !== 0 || !c.power || c.power.capacity <= 0) return null;
|
||||
const target = round(c.power.capacity * 0.6, 10);
|
||||
return target > Math.floor(c.power.stored) && target <= c.power.capacity ? { param: null, target } : null;
|
||||
},
|
||||
text: (n) => `Halte einen Stromüberschuss: fülle den Speicher auf ${fmt(n)} Strom`,
|
||||
},
|
||||
sturmfahrt: {
|
||||
icon: "sturm",
|
||||
spec: (t, c) => (t > 0 && balance.weather && canSail(c) ? { param: null, target: 1 } : null),
|
||||
text: () => "Bringe eine Mission trotz Sturm erfolgreich ans Ziel",
|
||||
},
|
||||
erkundung: {
|
||||
icon: "nachrichtendienst",
|
||||
spec: (t, c) => (canScout(c) ? pick([{ param: null, target: 1 }, { param: null, target: 2 }], t) : null),
|
||||
text: (n) => `Erkunde ${n === 1 ? "ein Ziel" : `${n} Ziele`} erfolgreich mit dem Nachrichtendienst`,
|
||||
},
|
||||
forschung: {
|
||||
icon: "forschungsamt",
|
||||
spec: (t, c) => (t === 1 && lvl(c, "forschungsamt") >= 1 ? { param: null, target: 1 } : null),
|
||||
@@ -239,7 +283,7 @@ export const KINDS: Record<string, KindDef> = {
|
||||
};
|
||||
|
||||
/** Arten, deren Fortschritt aus dem Zustand gelesen wird (beim Abruf), nicht aus Ereignissen. */
|
||||
export const DERIVED_KINDS = new Set(["lager", "produktion", "nachricht", "kommando"]);
|
||||
export const DERIVED_KINDS = new Set(["lager", "produktion", "nachricht", "kommando", "speicherwerk", "stromspeicher"]);
|
||||
|
||||
export function challengeText(kind: string, target: number, param: string | null): string {
|
||||
return KINDS[kind]?.text(target, param) ?? kind;
|
||||
@@ -252,10 +296,10 @@ export function challengeIcon(kind: string): string {
|
||||
// ---------------------------------------------------------------- Auswahl und Belohnung
|
||||
|
||||
/** Kontext aus dem (fortgeschriebenen) Stützpunkt. */
|
||||
export function poolContext(state: BaseState, extra: { others: boolean; raidsPossible: boolean }): PoolContext {
|
||||
export function poolContext(state: BaseState, extra: { others: boolean; raidsPossible: boolean }, mods?: Modifiers): PoolContext {
|
||||
const units: Record<string, number> = {};
|
||||
for (const src of [state.units, state.unitsAway]) for (const [id, n] of Object.entries(src ?? {})) units[id] = (units[id] ?? 0) + n;
|
||||
const rates = productionRates(state, balance);
|
||||
const rates = productionRates(state, balance, mods);
|
||||
const production: ResourceMap = {};
|
||||
for (const r of balance.resources) production[r] = (rates.buildingPerHour[r] ?? 0) + (balance.baseTricklePerHour[r] ?? 0);
|
||||
const harbor = state.buildings.hafenkommandantur ?? 0;
|
||||
@@ -264,14 +308,20 @@ export function poolContext(state: BaseState, extra: { others: boolean; raidsPos
|
||||
levels: { ...state.buildings },
|
||||
units,
|
||||
resources: { ...state.resources },
|
||||
capacity: storageCapacity(state, balance),
|
||||
capacity: storageCapacity(state, balance, mods),
|
||||
production,
|
||||
marketOpen: harbor >= (balance.buildings.hafenkommandantur.marketFromLevel ?? 3),
|
||||
raidsPossible: extra.raidsPossible,
|
||||
others: extra.others,
|
||||
...((state.buildings.speicherwerk ?? 0) >= 1 ? { power: powerOf(state, mods) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function powerOf(state: BaseState, mods?: Modifiers): { stored: number; capacity: number } {
|
||||
const p = powerAt(state, state.resUpdatedAt, balance, mods);
|
||||
return { stored: p.stored, capacity: p.storageCapacity };
|
||||
}
|
||||
|
||||
function hashSeed(text: string): number {
|
||||
let h = 2166136261;
|
||||
for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 16777619);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// die Auswertung von Ereignissen (Vorher/Nachher um den Handler, aufgerufen aus events.ts).
|
||||
// Fehler hier dürfen Spielereignisse und Befehle nie blockieren: alles läuft in einem eigenen Savepoint.
|
||||
import { and, asc, count, eq, gte, isNotNull, isNull, lt, ne, sql } from "drizzle-orm";
|
||||
import { protectionStatus, settle, type Counts, type ResourceMap, type TrainingOrder } from "@tidefront/game-core";
|
||||
import { protectionStatus, settle, type Counts, type Mission, type ResourceMap, type TrainingOrder } from "@tidefront/game-core";
|
||||
import { tables, type DbOrTx, type Tx } from "@tidefront/db";
|
||||
import { balance } from "./context.ts";
|
||||
import type { EventRow } from "./events.ts";
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
dayStartMs,
|
||||
drawDay,
|
||||
poolContext,
|
||||
STORM_MISSION_FROM,
|
||||
type PoolContext,
|
||||
type Tier,
|
||||
} from "./challenge-pool.ts";
|
||||
@@ -29,10 +30,11 @@ const dc = tables.dailyChallenge;
|
||||
export async function contextFor(tx: DbOrTx, playerId: number, atMs: number): Promise<PoolContext | null> {
|
||||
const b = await baseOfPlayer(tx, playerId);
|
||||
if (!b) return null;
|
||||
const state = settle(b.state, atMs, balance, await modsOf(tx, b, atMs));
|
||||
const mods = await modsOf(tx, b, atMs);
|
||||
const state = settle(b.state, atMs, balance, mods);
|
||||
const [o] = await tx.select({ n: count() }).from(tables.base).where(ne(tables.base.playerId, playerId));
|
||||
const raidsPossible = protectionStatus(state.protection, atMs, balance).reason !== "anfaengerschutz";
|
||||
return poolContext(state, { others: (o?.n ?? 0) > 0, raidsPossible });
|
||||
return poolContext(state, { others: (o?.n ?? 0) > 0, raidsPossible }, mods);
|
||||
}
|
||||
|
||||
async function dayRows(tx: DbOrTx, playerId: number, day: string): Promise<ChallengeRow[]> {
|
||||
@@ -134,6 +136,8 @@ export async function refreshDerived(tx: DbOrTx, playerId: number, rows: Challen
|
||||
else if (c && r.kind === "lager") value = Math.floor(c.resources[r.param ?? ""] ?? 0);
|
||||
else if (c && r.kind === "produktion") value = Math.floor(c.production[r.param ?? ""] ?? 0);
|
||||
else if (c && r.kind === "kommando") value = c.stage;
|
||||
else if (c && r.kind === "speicherwerk") value = c.levels.speicherwerk ?? 0;
|
||||
else if (c && r.kind === "stromspeicher") value = Math.floor(c.power?.stored ?? 0);
|
||||
const progress = Math.min(r.target, Math.max(r.progress, value));
|
||||
if (progress === r.progress) continue;
|
||||
const completedAt = progress >= r.target ? new Date(nowMs) : null;
|
||||
@@ -220,6 +224,10 @@ async function after(tx: Tx, ev: EventRow, due: number, snap: NonNullable<Challe
|
||||
// Wrackgut: Ladung der Heimfahrt ohne die Beute.
|
||||
await trackProgress(tx, pid, "wrack", sumRes(m.cargoHome as ResourceMap) - loot, at);
|
||||
if (!r) return;
|
||||
// Wetter: Mission trotz Sturm auf der Route erfolgreich (Sturmanteil bei Abfahrt).
|
||||
const storm = (m.plan as Mission | null)?.weather?.storminess ?? 0;
|
||||
const success = r.kind === "aufklaerung" || r.kind === "transport" || ((r.kind === "ueberfall" || r.kind === "weltereignis") && r.winner === "attacker");
|
||||
if (storm >= STORM_MISSION_FROM && success) await trackProgress(tx, pid, "sturmfahrt", 1, at);
|
||||
if (r.kind === "aufklaerung") await trackProgress(tx, pid, "aufklaerung", 1, at);
|
||||
else if (r.kind === "transport") await trackProgress(tx, pid, "transport", 1, at);
|
||||
else if (r.kind === "ueberfall") {
|
||||
|
||||
@@ -32,6 +32,7 @@ import { diplomacyBlock } from "./alliance-core.ts";
|
||||
import { veteranView } from "./veterans.ts";
|
||||
import { TECH_NAMES } from "./research.ts";
|
||||
import { scoutWithDisinfo } from "./espionage.ts";
|
||||
import { trackProgress } from "./challenges.ts";
|
||||
import { KIND_TEXT, openWorldEvents, systemMessage } from "./world-events.ts";
|
||||
|
||||
const HOUR_MS = 3600000;
|
||||
@@ -233,6 +234,8 @@ export const spyArrive: Handler = async (tx, ev, due) => {
|
||||
report: { spy: dice, ...detail },
|
||||
});
|
||||
await back(reportId, true);
|
||||
// Tagesbefehl „erkundung“: erfolgreiche Erkundung (Hafen oder Kartell).
|
||||
if (spy.kind === "erkunden" || spy.kind === "kartell") await trackProgress(tx, pid, "erkundung", 1, { atMs: due });
|
||||
push.push({ playerId: pid, notice: { kind: "report", url: "/?tab=meldungen", tag: `spy-${m.id}`, title: `Spionagebericht: ${KIND_TITLE[spy.kind]}`, body: `Auftrag gegen ${targetName} gelungen (Wurf ${roll.roll}, nötig ≤ ${roll.threshold}).` } });
|
||||
return { notify, push };
|
||||
};
|
||||
|
||||
@@ -7,6 +7,8 @@ import { balance, type NoticeJob } from "./context.ts";
|
||||
import type { EventRow, Handler } from "./events.ts";
|
||||
import { lockBase, readBase, scheduleEvent } from "./store.ts";
|
||||
import { amounts, clock, fmtInt, minutesText, nameOf } from "./names.ts";
|
||||
import { modsOf } from "./modifiers.ts";
|
||||
import { detectedAtOf, isDetected, markDetected, warnFactor } from "./radar.ts";
|
||||
|
||||
export type Snapshot =
|
||||
| { kind: "build"; order: BuildOrder | null }
|
||||
@@ -121,6 +123,7 @@ export async function noticesAfter(tx: Tx, ev: EventRow, due: number, snap: Snap
|
||||
if (snap.status === null) return [];
|
||||
const [m] = await tx.select().from(tables.mission).where(eq(tables.mission.id, Number(ev.payload.missionId)));
|
||||
if (!m || m.status === snap.status) return [];
|
||||
if (ev.type === "mission_return" && m.status === "done" && m.playerId !== null && m.type === "spionage") return spyReturnNotice(tx, m);
|
||||
if (ev.type === "mission_return" && m.status === "done" && m.playerId !== null) {
|
||||
const cargo = amounts(m.cargoHome as Record<string, number>);
|
||||
return [{ playerId: m.playerId, notice: {
|
||||
@@ -132,6 +135,27 @@ export async function noticesAfter(tx: Tx, ev: EventRow, due: number, snap: Snap
|
||||
return [];
|
||||
}
|
||||
|
||||
const SPY_KIND: Record<string, string> = { erkunden: "Erkunden", sabotage: "Sabotage", desinformation: "Desinformation", kartell: "Kartell-Aufklärung" };
|
||||
|
||||
/** Heimkehr eines Spionageauftrags: eigene Meldung „Spione zurück“ mit Art und Ergebnis (aus dem Bericht). */
|
||||
async function spyReturnNotice(tx: Tx, m: { id: number; playerId: number | null; plan: unknown; reportId: number | null }): Promise<NoticeJob[]> {
|
||||
const spy = (m.plan as { spy?: { kind?: string } } | null)?.spy;
|
||||
const kind = SPY_KIND[spy?.kind ?? ""] ?? "Spionage";
|
||||
let result = "Auftrag ausgeführt";
|
||||
let target = "";
|
||||
if (m.reportId !== null) {
|
||||
const [r] = await tx.select({ winner: tables.battleReport.winner, report: tables.battleReport.report }).from(tables.battleReport).where(eq(tables.battleReport.id, m.reportId));
|
||||
const info = (r?.report as { spy?: { aborted?: string; targetName?: string } } | undefined)?.spy;
|
||||
target = info?.targetName ?? "";
|
||||
result = info?.aborted ? "abgebrochen" : r?.winner === "attacker" ? "gelungen" : result;
|
||||
}
|
||||
const facts: [string, string][] = [["Auftrag", kind], ...(target ? [["Ziel", target] as [string, string]] : []), ["Ergebnis", result]];
|
||||
return [{ playerId: m.playerId!, notice: {
|
||||
kind: "fleet", url: "/?tab=meldungen", tag: `spy-back-${m.id}`, title: "Spione zurück",
|
||||
body: `${kind}${target ? ` gegen ${target}` : ""}: ${result}. Die Spione sind wieder im Hafen.`, facts,
|
||||
} }];
|
||||
}
|
||||
|
||||
/**
|
||||
* Plant die Radar-Vorwarnung für einen Angriff auf einen Spielerhafen:
|
||||
* fällig zu max(jetzt, Ankunft − Vorwarnzeit). Bei gleicher Fälligkeit läuft die Ankunft zuerst
|
||||
@@ -153,12 +177,29 @@ export async function scheduleAttackWarning(
|
||||
return due;
|
||||
}
|
||||
|
||||
/** Ereignis attack_warning: Angriff erkannt, solange der Verband noch unterwegs ist. */
|
||||
/** Spätestens so oft prüft eine aufgeschobene Warnung das Radar erneut (Strom oder Nebel können sich bessern). */
|
||||
export const RADAR_RECHECK_MS = 15 * 60000;
|
||||
|
||||
/**
|
||||
* Ereignis attack_warning: Angriff erkannt, solange der Verband noch unterwegs ist. Geprüft wird mit dem Radar zum
|
||||
* Fälligkeitszeitpunkt (Strom, Sabotage, Nebel); ist er noch nicht erfasst, wird neu geplant. Erkannt wird im Plan
|
||||
* gemerkt (radar.ts) – Anzeige und Push fallen danach nicht mehr zurück.
|
||||
*/
|
||||
export const attackWarning: Handler = async (tx, ev, due) => {
|
||||
const [m] = await tx.select().from(tables.mission).where(eq(tables.mission.id, Number(ev.payload.missionId)));
|
||||
if (!m || m.status !== "outbound" || m.targetKind !== "base" || m.targetId === null) return { notify: [] };
|
||||
const b = await readBase(tx, m.targetId);
|
||||
if (!b) return { notify: [] };
|
||||
if (detectedAtOf(m.plan) === null) {
|
||||
const mods = await modsOf(tx, b, due);
|
||||
const warn = radarWarningMinutes(settle(b.state, due, balance, mods), balance, mods);
|
||||
if (!isDetected(m, due, warn)) {
|
||||
const next = Math.min(m.arriveAt.getTime() - warn * warnFactor(m.plan) * 60000, due + RADAR_RECHECK_MS);
|
||||
if (next < m.arriveAt.getTime()) await scheduleEvent(tx, "attack_warning", Math.max(next, due + 1), { missionId: m.id }, b.id);
|
||||
return { notify: [] };
|
||||
}
|
||||
await markDetected(tx, [m.id], due);
|
||||
}
|
||||
let attacker = "Freibeuter-Kartell";
|
||||
if (m.playerId !== null) {
|
||||
const [p] = await tx.select({ name: tables.player.name }).from(tables.player).where(eq(tables.player.id, m.playerId));
|
||||
|
||||
@@ -7,6 +7,7 @@ export * from "./audit.ts";
|
||||
export * from "./seed.ts";
|
||||
export * from "./scoring.ts";
|
||||
export * from "./season.ts";
|
||||
export * from "./season-alliances.ts";
|
||||
export * from "./social.ts";
|
||||
export { baseOfPlayer } from "./store.ts";
|
||||
export * from "./account.ts";
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// Radar-Erkennung anfliegender Angriffe: einmal erkannt bleibt erkannt. Der Erkennungszeitpunkt steht im Plan der
|
||||
// Mission (plan.detectedAtMs); fällt das Radar danach aus (Strommangel, Sabotage, Nebel), bleibt der Angriff sichtbar.
|
||||
// Gesetzt wird er vom Ereignis attack_warning (Push) und von den Lesemodellen, sobald die aktuelle Vorwarnzeit ihn erfasst.
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { isAttackDetected, type Mission } from "@tidefront/game-core";
|
||||
import { tables, type DbOrTx } from "@tidefront/db";
|
||||
|
||||
/** Tarnfaktor eines Verbands (Mission.warningFactor), 1 ohne Tarnung. */
|
||||
export function warnFactor(plan: unknown): number {
|
||||
return (plan as Mission | null)?.warningFactor ?? 1;
|
||||
}
|
||||
|
||||
/** Gespeicherter Erkennungszeitpunkt oder null. */
|
||||
export function detectedAtOf(plan: unknown): number | null {
|
||||
const t = (plan as Mission | null)?.detectedAtMs;
|
||||
return typeof t === "number" ? t : null;
|
||||
}
|
||||
|
||||
/** Erkannt: schon früher erkannt oder jetzt innerhalb der aktuellen Vorwarnzeit (`warnMinutes` ohne Tarnung). */
|
||||
export function isDetected(m: { arriveAt: Date; plan: unknown }, nowMs: number, warnMinutes: number): boolean {
|
||||
const at = detectedAtOf(m.plan);
|
||||
if (at !== null && nowMs >= at) return true;
|
||||
return isAttackDetected(m.arriveAt.getTime(), nowMs, warnMinutes * warnFactor(m.plan));
|
||||
}
|
||||
|
||||
/** Merkt die Erkennung (nur wo noch keine steht, nur auf der Hinfahrt); idempotent. */
|
||||
export async function markDetected(db: DbOrTx, missionIds: number[], atMs: number): Promise<void> {
|
||||
if (!missionIds.length) return;
|
||||
await db
|
||||
.update(tables.mission)
|
||||
.set({ plan: sql`jsonb_set(${tables.mission.plan}, '{detectedAtMs}', to_jsonb(${atMs}::bigint))` })
|
||||
.where(and(
|
||||
inArray(tables.mission.id, missionIds),
|
||||
eq(tables.mission.status, "outbound"),
|
||||
sql`${tables.mission.plan}->'detectedAtMs' is null`,
|
||||
));
|
||||
}
|
||||
|
||||
/** Filtert erkannte Angriffe (`rows`: anfliegend auf einen Hafen) und merkt neu erkannte. */
|
||||
export async function detectIncoming<T extends { id: number; arriveAt: Date; plan: unknown }>(
|
||||
db: DbOrTx,
|
||||
rows: T[],
|
||||
nowMs: number,
|
||||
warnMinutes: number,
|
||||
): Promise<T[]> {
|
||||
const seen = rows.filter((m) => isDetected(m, nowMs, warnMinutes));
|
||||
await markDetected(db, seen.filter((m) => detectedAtOf(m.plan) === null).map((m) => m.id), nowMs);
|
||||
return seen;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// Allianzwertung zum Saisonende: Summe der Mitgliederpunkte (Endstand) je Allianz, Rangliste mit gleichen Plätzen
|
||||
// bei Punktgleichheit. Gespeichert in season_alliance_result; gelesen von der Ruhmeshalle (hallOfFame).
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import { tables, type DbOrTx, type Tx } from "@tidefront/db";
|
||||
|
||||
export interface AllianceStanding {
|
||||
allianceId: number;
|
||||
name: string;
|
||||
tag: string;
|
||||
rank: number;
|
||||
members: number;
|
||||
total: number;
|
||||
playerIds: number[];
|
||||
}
|
||||
|
||||
/** Rangliste der Allianzen aus den Gesamtpunkten der Spieler (`totals`: playerId → Punkte zum Saisonende). */
|
||||
export async function allianceStandings(db: DbOrTx, totals: Map<number, number>): Promise<AllianceStanding[]> {
|
||||
const rows = await db
|
||||
.select({ allianceId: tables.allianceMember.allianceId, playerId: tables.allianceMember.playerId, name: tables.alliance.name, tag: tables.alliance.tag })
|
||||
.from(tables.allianceMember)
|
||||
.innerJoin(tables.alliance, eq(tables.alliance.id, tables.allianceMember.allianceId));
|
||||
const by = new Map<number, AllianceStanding>();
|
||||
for (const r of rows) {
|
||||
const a = by.get(r.allianceId) ?? { allianceId: r.allianceId, name: r.name, tag: r.tag, rank: 0, members: 0, total: 0, playerIds: [] };
|
||||
a.members++;
|
||||
a.total += totals.get(r.playerId) ?? 0;
|
||||
a.playerIds.push(r.playerId);
|
||||
by.set(r.allianceId, a);
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
/** Saisonende: Allianzwertung speichern (idempotent je Saison und Allianz). */
|
||||
export async function saveAllianceStandings(tx: Tx, seasonId: number, list: AllianceStanding[]): Promise<void> {
|
||||
if (list.length === 0) return;
|
||||
await tx
|
||||
.insert(tables.seasonAllianceResult)
|
||||
.values(list.map((a) => ({ seasonId, allianceId: a.allianceId, name: a.name, tag: a.tag, rank: a.rank, members: a.members, total: a.total, playerIds: a.playerIds })))
|
||||
.onConflictDoNothing();
|
||||
}
|
||||
|
||||
/** Allianzwertungen beendeter Saisons, je Saison nach Rang; `own` markiert die Allianz der Spielerin damals. */
|
||||
export async function allianceResultsFor(db: DbOrTx, seasonIds: number[], playerId: number) {
|
||||
if (seasonIds.length === 0) return new Map<number, { rank: number; name: string; tag: string; members: number; total: number; own: boolean }[]>();
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(tables.seasonAllianceResult)
|
||||
.where(inArray(tables.seasonAllianceResult.seasonId, seasonIds))
|
||||
.orderBy(tables.seasonAllianceResult.rank, tables.seasonAllianceResult.name);
|
||||
const out = new Map<number, { rank: number; name: string; tag: string; members: number; total: number; own: boolean }[]>();
|
||||
for (const r of rows) {
|
||||
const list = out.get(r.seasonId) ?? [];
|
||||
list.push({ rank: r.rank, name: r.name, tag: r.tag, members: r.members, total: r.total, own: (r.playerIds as number[]).includes(playerId) });
|
||||
out.set(r.seasonId, list);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { resetChallenges } from "./challenges.ts";
|
||||
import { expireOffers } from "./player-trade.ts";
|
||||
import { clearWorldEvents } from "./world-events.ts";
|
||||
import { clearMarketNews } from "./market-news.ts";
|
||||
import { allianceResultsFor, allianceStandings, saveAllianceStandings } from "./season-alliances.ts";
|
||||
|
||||
const DAY_MS = 86400000;
|
||||
|
||||
@@ -115,6 +116,12 @@ export const seasonEnd: Handler = async (tx, ev, due) => {
|
||||
.onConflictDoNothing();
|
||||
}
|
||||
|
||||
// Allianzwertung: Summe der Mitgliederpunkte zum Saisonende.
|
||||
const allianceList = await allianceStandings(tx, new Map(ranked.map((r) => [r.playerId, r.total])));
|
||||
await saveAllianceStandings(tx, s.id, allianceList);
|
||||
const ownAlliance = new Map(allianceList.flatMap((a) => a.playerIds.map((id) => [id, a] as const)));
|
||||
const topAlliance = allianceList[0];
|
||||
|
||||
// 2. Systemnachricht an alle Spieler.
|
||||
const winner = ranked[0];
|
||||
const byId = new Map(ranked.map((r) => [r.playerId, r]));
|
||||
@@ -129,6 +136,9 @@ export const seasonEnd: Handler = async (tx, ev, due) => {
|
||||
const a = awards.get(p.playerId) ?? [];
|
||||
if (a.length > 0) lines.push(`Deine Auszeichnungen: ${a.map(awardText).join(", ")}.`);
|
||||
} else lines.push("Du warst in dieser Saison nicht platziert.");
|
||||
if (topAlliance && topAlliance.total > 0) lines.push(`Stärkste Allianz: [${topAlliance.tag}] ${topAlliance.name} mit ${topAlliance.total} Punkten.`);
|
||||
const al = ownAlliance.get(p.playerId);
|
||||
if (al) lines.push(`Deine Allianz [${al.tag}] ${al.name}: Platz ${al.rank} von ${allianceList.length} mit ${al.total} Punkten.`);
|
||||
lines.push(`Saison ${s.number + 1} beginnt jetzt. Wähle einen neuen Hafen.`);
|
||||
return { fromPlayerId: null, toPlayerId: p.playerId, subject: `Saison ${s.number}: Endstand`, body: lines.join("\n"), createdAt: new Date(due) };
|
||||
}));
|
||||
@@ -218,6 +228,7 @@ export async function hallOfFame(db: DbOrTx, playerId: number) {
|
||||
.orderBy(desc(tables.season.number))
|
||||
.limit(50);
|
||||
if (seasons.length === 0) return [];
|
||||
const allianceResults = await allianceResultsFor(db, seasons.map((s) => s.id), playerId);
|
||||
const results = await db
|
||||
.select()
|
||||
.from(tables.seasonResult)
|
||||
@@ -240,6 +251,8 @@ export async function hallOfFame(db: DbOrTx, playerId: number) {
|
||||
return [a, r ? { name: r.playerName, value: r[a.slice(5) as "ausbau"] } : null];
|
||||
}),
|
||||
) as Record<string, { name: string; value: number } | null>,
|
||||
/** Allianzwertung zum Saisonende (Summe der Mitgliederpunkte), nach Rang. */
|
||||
alliances: allianceResults.get(s.id) ?? [],
|
||||
own: own ? { ...pick(own), ausbau: own.ausbau, militaer: own.militaer, kampf: own.kampf, beute: own.beute, befehle: own.befehle } : null,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
commandPoints,
|
||||
harborCreditLimit,
|
||||
harborMarketUnlocked,
|
||||
isAttackDetected,
|
||||
isNestRespawned,
|
||||
maxAllowedLevel,
|
||||
missionSlots,
|
||||
@@ -46,12 +45,16 @@ import { researchView } from "./research.ts";
|
||||
import { diplomacyBlock } from "./alliance-core.ts";
|
||||
import { intelView } from "./espionage.ts";
|
||||
import { gridView, missionWeather } from "./weather.ts";
|
||||
import { detectIncoming } from "./radar.ts";
|
||||
|
||||
/** Ist ein feindlicher Verband auf dem Anmarsch und schon vom Radar erfasst? (Radar mit `mods`, Tarnung je Verband.) */
|
||||
/**
|
||||
* Ist ein feindlicher Verband auf dem Anmarsch und schon vom Radar erfasst? (Radar mit `mods`, Tarnung je Verband;
|
||||
* einmal erkannt bleibt erkannt, radar.ts.)
|
||||
*/
|
||||
export async function incomingDetected(tx: DbOrTx, baseId: number, state: BaseState, nowMs: number, mods?: Modifiers): Promise<boolean> {
|
||||
const warn = radarWarningMinutes(state, balance, mods);
|
||||
const rows = await tx
|
||||
.select({ arriveAt: tables.mission.arriveAt, plan: tables.mission.plan })
|
||||
.select({ id: tables.mission.id, arriveAt: tables.mission.arriveAt, plan: tables.mission.plan })
|
||||
.from(tables.mission)
|
||||
.where(and(
|
||||
eq(tables.mission.targetKind, "base"),
|
||||
@@ -59,12 +62,7 @@ export async function incomingDetected(tx: DbOrTx, baseId: number, state: BaseSt
|
||||
eq(tables.mission.status, "outbound"),
|
||||
inArray(tables.mission.type, ["ueberfall", "kartell"]),
|
||||
));
|
||||
return rows.some((r) => isAttackDetected(r.arriveAt.getTime(), nowMs, warn * warnFactor(r.plan)));
|
||||
}
|
||||
|
||||
/** Tarnfaktor eines Verbands (Mission.warningFactor), 1 ohne Tarnung. */
|
||||
function warnFactor(plan: unknown): number {
|
||||
return (plan as Mission | null)?.warningFactor ?? 1;
|
||||
return (await detectIncoming(tx, rows, nowMs, warn)).length > 0;
|
||||
}
|
||||
|
||||
export async function baseView(engine: Engine, playerId: number) {
|
||||
@@ -118,10 +116,11 @@ export async function baseView(engine: Engine, playerId: number) {
|
||||
const senders = senderIds.length
|
||||
? new Map((await engine.db.select({ id: tables.base.id, name: tables.base.name }).from(tables.base).where(inArray(tables.base.id, senderIds))).map((r) => [r.id, r.name]))
|
||||
: new Map<number, string>();
|
||||
// Spionageaufträge bleiben unsichtbar (kein Radar); Angriffe ab Erkennung (einmal erkannt bleibt erkannt).
|
||||
const attacks = incomingRows.filter((m) => m.type !== "spionage" && m.type !== "transport");
|
||||
const seen = new Set((await detectIncoming(engine.db, attacks, nowMs, warn)).map((m) => m.id));
|
||||
const incoming = incomingRows
|
||||
// Spionageaufträge bleiben unsichtbar (kein Radar).
|
||||
.filter((m) => m.type !== "spionage")
|
||||
.filter((m) => m.type === "transport" || isAttackDetected(m.arriveAt.getTime(), nowMs, warn * warnFactor(m.plan)))
|
||||
.filter((m) => m.type === "transport" || seen.has(m.id))
|
||||
.map((m) => ({
|
||||
id: m.id,
|
||||
type: m.type,
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
type AttackerInput,
|
||||
type Counts,
|
||||
type Mission,
|
||||
type Modifiers,
|
||||
type ResourceMap,
|
||||
} from "@tidefront/game-core";
|
||||
import { hexAtLonLat, hexCenter, hexDistanceKm } from "@tidefront/world";
|
||||
@@ -28,7 +29,8 @@ import {
|
||||
type Hex, type WorldEventRow,
|
||||
} from "./world-events.ts";
|
||||
import { siegeTick } from "./world-events-run.ts";
|
||||
import { modifiersFor } from "./modifiers.ts";
|
||||
import { modifiersFor, modsOf } from "./modifiers.ts";
|
||||
import { battleWeather, missionWeather } from "./weather.ts"; // Wetter wie bei normalen Missionen (v1.6)
|
||||
|
||||
export interface EventMissionInput {
|
||||
type: string;
|
||||
@@ -50,12 +52,17 @@ function aim(ev: WorldEventRow | null, playerId: number, own: BaseRow, input: Ev
|
||||
return hexAtLonLat(hit.point.lon, hit.point.lat);
|
||||
}
|
||||
|
||||
function plan(own: BaseRow, input: EventMissionInput, target: Hex, active: number, nowMs: number) {
|
||||
/** Planung wie bei normalen Missionen: Modifikatoren des Spielers und Wetter entlang der Route (Sturm). */
|
||||
function plan(own: BaseRow, input: EventMissionInput, target: Hex, active: number, nowMs: number, mods: Modifiers) {
|
||||
return planMission(
|
||||
own.state,
|
||||
{ type: input.type, units: input.units, origin: hexCenter(own.col, own.row), target: hexCenter(target.col, target.row), activeMissions: active },
|
||||
{
|
||||
type: input.type, units: input.units, origin: hexCenter(own.col, own.row), target: hexCenter(target.col, target.row), activeMissions: active,
|
||||
weather: missionWeather(own.col, own.row, target.col, target.row, nowMs),
|
||||
},
|
||||
nowMs,
|
||||
balance,
|
||||
mods,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -70,7 +77,7 @@ export async function launchAgainstEvent(
|
||||
): Promise<{ ok: true; missionId: number; arriveAtMs: number } | { ok: false; code: string }> {
|
||||
const ev = await readWorldEvent(tx, input.eventId);
|
||||
const target = aim(ev, playerId, own, input, nowMs);
|
||||
const r = plan(own, input, target, await activeMissionCount(tx, own.id), nowMs);
|
||||
const r = plan(own, input, target, await activeMissionCount(tx, own.id), nowMs, await modsOf(tx, own, nowMs));
|
||||
if (!r.ok) return r;
|
||||
if (ev!.kind !== "grossflotte" && r.mission.arriveAtMs >= ev!.endsAt.getTime()) return { ok: false, code: "too_late" };
|
||||
await saveBase(tx, own.id, r.base);
|
||||
@@ -97,9 +104,11 @@ export async function previewAgainstEvent(db: DbOrTx, playerId: number, own: Bas
|
||||
throw err;
|
||||
}
|
||||
const distanceKm = hexDistanceKm(own, target);
|
||||
const r = plan({ ...own, state: settle(own.state, nowMs, balance) }, input, target, await activeMissionCount(db, own.id), nowMs);
|
||||
if (!r.ok) return { ok: false as const, code: r.code, distanceKm };
|
||||
if (ev!.kind !== "grossflotte" && r.mission.arriveAtMs >= ev!.endsAt.getTime()) return { ok: false as const, code: "too_late", distanceKm };
|
||||
const mods = await modsOf(db, own, nowMs);
|
||||
const weather = missionWeather(own.col, own.row, target.col, target.row, nowMs);
|
||||
const r = plan({ ...own, state: settle(own.state, nowMs, balance, mods) }, input, target, await activeMissionCount(db, own.id), nowMs, mods);
|
||||
if (!r.ok) return { ok: false as const, code: r.code, distanceKm, weather };
|
||||
if (ev!.kind !== "grossflotte" && r.mission.arriveAtMs >= ev!.endsAt.getTime()) return { ok: false as const, code: "too_late", distanceKm, weather };
|
||||
return {
|
||||
ok: true as const,
|
||||
distanceKm,
|
||||
@@ -109,6 +118,8 @@ export async function previewAgainstEvent(db: DbOrTx, playerId: number, own: Bas
|
||||
returnAtMs: r.mission.returnAtMs,
|
||||
target: { kind: "event", own: false },
|
||||
intercept: target,
|
||||
weather,
|
||||
weatherFactor: r.mission.weather?.shipFactor ?? 1,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -168,7 +179,7 @@ export async function eventMissionArrive(
|
||||
const modifiers = await modifiersFor(tx, pid, { state: origin?.state ?? null, nowMs: due });
|
||||
const attacker: AttackerInput = { units: plan.units, versorgungsmangel: origin?.state.versorgungsmangel ?? false, modifiers };
|
||||
const seed = randomSeed();
|
||||
const res = resolveBattle(attacker, { units: activeUnits(ev.units), defenses: {} }, balance, seed);
|
||||
const res = resolveBattle(attacker, { units: activeUnits(ev.units), defenses: {} }, balance, seed, battleWeather(m.targetCol, m.targetRow, due));
|
||||
if (!res.ok) throw new Error(`battle: ${res.code}`);
|
||||
const { report: raw, destroyed } = strandTroops(res.report, balance);
|
||||
const before = forceHp(activeUnits(ev.units), balance);
|
||||
|
||||
@@ -27,19 +27,23 @@ import {
|
||||
} from "./world-events.ts";
|
||||
import { worldEventSpawn } from "./world-events-spawn.ts";
|
||||
import { modsOf } from "./modifiers.ts";
|
||||
import { battleWeather } from "./weather.ts"; // Wetter am Kampfort wie bei normalen Kämpfen (v1.6)
|
||||
|
||||
const HOUR_MS = 3600000;
|
||||
const none = (): HandlerResult => ({ notify: [] });
|
||||
|
||||
/** Belagerung: Abzug von productionPenalty der Gebäudeproduktion seit dem letzten Abzug bis `untilMs`. */
|
||||
/** Belagerung: Abzug von productionPenalty der (modifizierten) Gebäudeproduktion seit dem letzten Abzug bis `untilMs`. */
|
||||
async function siegeTick(tx: Tx, ev: WorldEventRow, untilMs: number): Promise<number[]> {
|
||||
const from = ev.data.lastTickMs ?? ev.startsAt.getTime();
|
||||
const to = Math.min(untilMs, ev.endsAt.getTime());
|
||||
if (to <= from || ev.targetBaseId === null) return [];
|
||||
const b = await lockBase(tx, ev.targetBaseId);
|
||||
if (!b) return [];
|
||||
const state = settle(b.state, to, balance);
|
||||
const r = applySiegePenalty(state.resources, productionRates(state, balance).buildingPerHour, storageCapacity(state, balance), (to - from) / HOUR_MS, balance);
|
||||
// Produktion wie überall über die Modifikatoren (Forschung, Sabotage, Strom, Wetter, Ereignisse).
|
||||
const mods = await modsOf(tx, b, to);
|
||||
const state = settle(b.state, to, balance, mods);
|
||||
const rates = productionRates(state, balance, mods).buildingPerHour;
|
||||
const r = applySiegePenalty(state.resources, rates, storageCapacity(state, balance, mods), (to - from) / HOUR_MS, balance);
|
||||
state.resources = r.resources;
|
||||
await saveBase(tx, b.id, state);
|
||||
const data = { ...ev.data, lastTickMs: to, deducted: addRes(ev.data.deducted ?? {}, r.deducted) };
|
||||
@@ -95,7 +99,7 @@ const worldEventAttack: Handler = async (tx, ev, due) => {
|
||||
const state = settle(b.state, due, balance, mods);
|
||||
const attacker = armadaAttacker(units, balance);
|
||||
const seed = randomSeed();
|
||||
const res = resolveBattle(attacker, defenderFromBase(state, balance, mods), balance, seed);
|
||||
const res = resolveBattle(attacker, defenderFromBase(state, balance, mods), balance, seed, battleWeather(b.col, b.row, due));
|
||||
if (!res.ok) throw new Error(`battle: ${res.code}`);
|
||||
const report = res.report;
|
||||
await saveBase(tx, b.id, applyDefenseResult(state, report, due, balance, mods));
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
// Integrationstests für geschlossene Lücken im Regelkern (echtes PostgreSQL, wird geleert): Wetter bei Weltereignissen,
|
||||
// Radar „einmal erkannt bleibt erkannt“, Meldung „Spione zurück“, Belagerung und Admin-Statistik mit Modifikatoren,
|
||||
// Tagesbefehle zu Strom, Wetter und Nachrichtendienst, Allianzwertung im Saisonergebnis.
|
||||
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 { nestSites, isCoast, hexDistanceKm, COLS, ROWS } from "@tidefront/world";
|
||||
import {
|
||||
productionRates, settle, spyRollOf, worldEventsBalance,
|
||||
type BaseState, type Mission, type SpyMission, type WorldEventKind,
|
||||
} from "@tidefront/game-core";
|
||||
import {
|
||||
adminStats, balance, baseView, CHALLENGE_KINDS, chooseBase, dailyView, dayKey, drawDay, hallOfFame, launchMission,
|
||||
missionPreview, modifiersFor, poolContext, processDue, register, registerModifierSource, runningSeason, seasonEnd, seed,
|
||||
spawnWorldEvent, spyLaunch, type Engine, type NoticeJob,
|
||||
} 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", 10);
|
||||
const pushed: NoticeJob[] = [];
|
||||
const engine: Engine = { db, notify: () => {}, log: () => {}, push: (jobs) => pushed.push(...jobs) };
|
||||
let keyN = 0;
|
||||
const key = () => `l${++keyN}-${Date.now()}`;
|
||||
const rich = { stahl: 50000, treibstoff: 50000, elektronik: 50000, proviant: 50000 };
|
||||
const SEED_OK = (() => { let s = 1; while (spyRollOf(s, 20) !== 1) s++; return s; })();
|
||||
const dc = tables.dailyChallenge;
|
||||
|
||||
function freeCoast(skip: number): { col: number; row: number } {
|
||||
const nests = new Set(nestSites().map((n) => `${n.col},${n.row}`));
|
||||
let k = 0;
|
||||
for (let row = 10; row < ROWS; row++) for (let col = 0; col < COLS; col++) {
|
||||
if (isCoast(col, row) && !nests.has(`${col},${row}`) && k++ === skip) return { col, row };
|
||||
}
|
||||
throw new Error("no coast");
|
||||
}
|
||||
|
||||
/** Freies Küstenfeld 100–400 km von `near` entfernt. */
|
||||
function coastNear(near: { col: number; row: number }, skip: number): { col: number; row: number } {
|
||||
const nests = new Set(nestSites().map((n) => `${n.col},${n.row}`));
|
||||
let k = 0;
|
||||
for (let row = Math.max(0, near.row - 5); row <= Math.min(ROWS - 1, near.row + 5); row++) {
|
||||
for (let col = Math.max(0, near.col - 5); col <= Math.min(COLS - 1, near.col + 5); col++) {
|
||||
const d = hexDistanceKm(near, { col, row });
|
||||
if (isCoast(col, row) && !nests.has(`${col},${row}`) && d >= 100 && d <= 400 && k++ === skip) return { col, row };
|
||||
}
|
||||
}
|
||||
throw new Error("no coast near");
|
||||
}
|
||||
|
||||
/** Spieler mit Hafen ohne Anfängerschutz. */
|
||||
async function newPlayer(name: string, field: number | { col: number; row: number }) {
|
||||
const p = await register(db, { inviteCode: "TEST", name, password: "geheim123" });
|
||||
const f = typeof field === "number" ? freeCoast(field) : field;
|
||||
const r = await chooseBase(engine, p.playerId, key(), { ...f, name: `Hafen ${name}`, nightShieldStartHour: null, tzOffsetMinutes: 0 });
|
||||
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; });
|
||||
return { playerId: p.playerId, baseId, ...f };
|
||||
}
|
||||
|
||||
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 missionRow(id: number) {
|
||||
const [m] = await db.select().from(tables.mission).where(eq(tables.mission.id, id));
|
||||
return m;
|
||||
}
|
||||
|
||||
async function spawn(kind: WorldEventKind, focusBaseId: number) {
|
||||
const s = await runningSeason(db);
|
||||
const r = await db.transaction((tx) => spawnWorldEvent(tx, Date.now(), kind, s!.id, 0, focusBaseId));
|
||||
assert.ok(r && r.kind === kind, "kein Ereignis");
|
||||
return r.id;
|
||||
}
|
||||
|
||||
async function runUntil(ms: number) {
|
||||
while ((await processDue(engine, ms, 500)) > 0);
|
||||
}
|
||||
|
||||
/** Keine Kartell-Überfälle und keine fremden Ereignisse im Testlauf. */
|
||||
async function quiet() {
|
||||
await db.delete(tables.gameEvent).where(sql`${tables.gameEvent.status} = 'pending' and (${tables.gameEvent.type} = 'raid_launch' or ${tables.gameEvent.type} like 'world_event%')`);
|
||||
}
|
||||
|
||||
async function setDaily(playerId: number, specs: { kind: string; target: number; param?: string | null }[]) {
|
||||
await dailyView(engine, playerId);
|
||||
for (const [slot, s] of specs.entries()) {
|
||||
await db.update(dc)
|
||||
.set({ kind: s.kind, target: s.target, param: s.param ?? null, progress: 0, completedAt: null, claimedAt: null, rerolled: false })
|
||||
.where(and(eq(dc.playerId, playerId), eq(dc.day, dayKey(Date.now())), eq(dc.slot, slot)));
|
||||
}
|
||||
}
|
||||
|
||||
/** Ankunft einer Mission auf jetzt vorziehen (Tagesbefehle zählen nur am selben Spieltag) und verarbeiten. */
|
||||
async function arriveNow(missionId: number) {
|
||||
await db.update(tables.gameEvent).set({ dueAt: new Date(Date.now() - 1000) })
|
||||
.where(and(eq(tables.gameEvent.status, "pending"), sql`(${tables.gameEvent.payload}->>'missionId')::int = ${missionId}`));
|
||||
await processDue(engine, Date.now());
|
||||
}
|
||||
|
||||
async function dailyOf(playerId: number, kind: string) {
|
||||
const [r] = await db.select().from(dc).where(and(eq(dc.playerId, playerId), eq(dc.day, dayKey(Date.now())), eq(dc.kind, kind)));
|
||||
return r;
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
test("Weltereignisse: Vorschau und Plan mit Wetter der Route, Kämpfe mit Wetter am Kampfort", async () => {
|
||||
const a = await newPlayer("Ziel", 90);
|
||||
const c = await newPlayer("Jaeger", coastNear(a, 3));
|
||||
await quiet();
|
||||
const id = await spawn("grossflotte", a.baseId);
|
||||
await patchBase(c.baseId, (s) => {
|
||||
s.units = { korvette: 6, landungsschiff: 1 }; s.resources.treibstoff = 1_000_000;
|
||||
s.buildings.kommandozentrale = 15; s.buildings.hafenkommandantur = 10;
|
||||
});
|
||||
const input = { type: "ueberfall", units: { korvette: 6, landungsschiff: 1 }, col: 0, row: 0, eventId: id };
|
||||
const pv = await missionPreview(engine, c.playerId, input) as { ok: boolean; weather?: { shipFactor: number }; weatherFactor?: number };
|
||||
assert.equal(pv.ok, true, JSON.stringify(pv));
|
||||
assert.ok(pv.weather, "Vorschau trägt das Wetter");
|
||||
assert.ok(pv.weatherFactor! >= 1 && pv.weatherFactor! <= 1 + balance.weather!.shipSlowMax);
|
||||
const m = await launchMission(engine, c.playerId, key(), input);
|
||||
assert.equal(m.ok, true, JSON.stringify(m));
|
||||
const row = await missionRow((m as { missionId: number }).missionId);
|
||||
assert.ok((row.plan as Mission).weather, "Plan trägt das Wetter");
|
||||
await runUntil((m as { arriveAtMs: number }).arriveAtMs + 1000);
|
||||
const [rep] = await db.select().from(tables.battleReport)
|
||||
.where(and(eq(tables.battleReport.kind, "weltereignis"), eq(tables.battleReport.attackerPlayerId, c.playerId)));
|
||||
assert.ok((rep.report as { battle: { weather?: unknown } }).battle.weather, "Kampf auf See mit Wetter");
|
||||
// Hafenangriff der Großflotte: ebenfalls mit Wetter.
|
||||
const [e] = await db.select().from(tables.worldEvent).where(eq(tables.worldEvent.id, id));
|
||||
const targets = (e.data as { targets: unknown[] }).targets.length;
|
||||
await runUntil(e.activeAt!.getTime() + targets * worldEventsBalance(balance).grossflotte.attackIntervalHours * HOUR + 1000);
|
||||
const [onA] = await db.select().from(tables.battleReport)
|
||||
.where(and(eq(tables.battleReport.kind, "weltereignis"), eq(tables.battleReport.defenderBaseId, a.baseId)));
|
||||
assert.ok(onA, "Hafenangriff fand statt");
|
||||
assert.ok((onA.report as { battle: { weather?: unknown } }).battle.weather, "Hafenangriff mit Wetter");
|
||||
});
|
||||
|
||||
test("Radar: einmal erkannt bleibt erkannt; Push-Warnung prüft das Radar zum Warnzeitpunkt", async () => {
|
||||
const r = await newPlayer("Radar", 30);
|
||||
const x = await newPlayer("Angreifer", 34);
|
||||
await patchBase(r.baseId, (s) => { s.buildings.radarstation = 4; s.buildings.kraftwerk = 3; s.resources = { ...rich }; });
|
||||
const insert = async (minutes: number) => {
|
||||
const arrive = Date.now() + minutes * 60000;
|
||||
const [m] = await db.insert(tables.mission).values({
|
||||
playerId: x.playerId, baseId: x.baseId, type: "ueberfall", targetKind: "base", targetId: r.baseId, targetCol: r.col,
|
||||
targetRow: r.row, plan: { type: "ueberfall", units: { korvette: 1 }, arriveAtMs: arrive }, status: "outbound", arriveAt: new Date(arrive),
|
||||
}).returning({ id: tables.mission.id });
|
||||
return m.id;
|
||||
};
|
||||
const first = await insert(5);
|
||||
let v = (await baseView(engine, r.playerId)).base!;
|
||||
assert.ok(v.radarWarningMinutes > 5, `Vorwarnzeit ${v.radarWarningMinutes}`);
|
||||
assert.ok(v.incoming.some((i) => i.id === first), "erkannt");
|
||||
assert.ok(typeof (await missionRow(first)).plan === "object" && ((await missionRow(first)).plan as Mission).detectedAtMs, "Erkennung gemerkt");
|
||||
// Radar fällt aus (Strommangel/Sabotage): der erkannte Angriff bleibt sichtbar, ein neuer wird nicht erkannt.
|
||||
await patchBase(r.baseId, (s) => { s.buildings.radarstation = 0; });
|
||||
const second = await insert(5);
|
||||
v = (await baseView(engine, r.playerId)).base!;
|
||||
assert.equal(v.radarWarningMinutes, 0);
|
||||
assert.ok(v.incoming.some((i) => i.id === first), "bleibt erkannt");
|
||||
assert.ok(!v.incoming.some((i) => i.id === second), "ohne Radar nicht erkannt");
|
||||
// Push: für den erkannten Angriff ja, für den unerkannten nicht (Radar zum Warnzeitpunkt).
|
||||
await db.delete(tables.gameEvent).where(sql`${tables.gameEvent.status} = 'pending' and ${tables.gameEvent.type} <> 'season_end'`);
|
||||
for (const id of [first, second]) {
|
||||
await db.insert(tables.gameEvent).values({ type: "attack_warning", dueAt: new Date(Date.now() - 1000), payload: { missionId: id }, baseId: r.baseId, status: "pending" });
|
||||
}
|
||||
pushed.length = 0;
|
||||
await processDue(engine, Date.now());
|
||||
const warns = pushed.filter((j) => j.notice.title === "Angriff erkannt");
|
||||
assert.deepEqual(warns.map((j) => j.notice.tag), [`attack-${first}`]);
|
||||
assert.equal(((await missionRow(second)).plan as Mission).detectedAtMs, undefined);
|
||||
// Mit Radar, aber außerhalb der Vorwarnzeit: Warnung wird neu geplant statt verschickt.
|
||||
await patchBase(r.baseId, (s) => { s.buildings.radarstation = 4; });
|
||||
const far = await insert(600);
|
||||
await db.insert(tables.gameEvent).values({ type: "attack_warning", dueAt: new Date(Date.now() - 1000), payload: { missionId: far }, baseId: r.baseId, status: "pending" });
|
||||
pushed.length = 0;
|
||||
await processDue(engine, Date.now());
|
||||
assert.equal(pushed.filter((j) => j.notice.tag === `attack-${far}`).length, 0);
|
||||
const [again] = await db.select().from(tables.gameEvent)
|
||||
.where(and(eq(tables.gameEvent.type, "attack_warning"), eq(tables.gameEvent.status, "pending"), sql`(${tables.gameEvent.payload}->>'missionId')::int = ${far}`));
|
||||
assert.ok(again && again.dueAt.getTime() > Date.now(), "neu geplant");
|
||||
await db.delete(tables.mission).where(eq(tables.mission.targetId, r.baseId));
|
||||
});
|
||||
|
||||
test("Spione zurück: eigene Meldung mit Art und Ergebnis; Erkundung zählt für den Tagesbefehl", async () => {
|
||||
const s = await newPlayer("Agentin", 50);
|
||||
const t = await newPlayer("Zielhafen", 54);
|
||||
await patchBase(s.baseId, (st) => {
|
||||
st.buildings.nachrichtendienst = 4; st.buildings.hafenkommandantur = 6; st.buildings.lagerkomplex = 8;
|
||||
st.units = { spion: 4 }; st.resources = { ...rich };
|
||||
});
|
||||
await setDaily(s.playerId, [{ kind: "erkundung", target: 1 }]);
|
||||
const r = await spyLaunch(engine, s.playerId, key(), { kind: "erkunden", col: t.col, row: t.row });
|
||||
assert.equal(r.ok, true, JSON.stringify(r));
|
||||
const id = (r as { missionId: number }).missionId;
|
||||
const plan = (await missionRow(id)).plan as SpyMission;
|
||||
await db.update(tables.mission).set({ plan: { ...plan, spy: { ...plan.spy, seed: SEED_OK } } }).where(eq(tables.mission.id, id));
|
||||
await arriveNow(id);
|
||||
assert.ok((await dailyOf(s.playerId, "erkundung")).completedAt, "Erkundung erfüllt");
|
||||
pushed.length = 0;
|
||||
await processDue(engine, plan.returnAtMs + 1000);
|
||||
const back = pushed.filter((j) => j.playerId === s.playerId && j.notice.kind === "fleet");
|
||||
assert.equal(back.length, 1);
|
||||
assert.equal(back[0].notice.title, "Spione zurück");
|
||||
assert.match(back[0].notice.body, /Erkunden gegen Hafen Zielhafen: gelungen/);
|
||||
});
|
||||
|
||||
test("Tagesbefehle: Strom, Wetter und Nachrichtendienst nur mit Gebäude; Sturmfahrt und Speicher zählen", async () => {
|
||||
for (const k of ["speicherwerk", "stromspeicher", "sturmfahrt", "erkundung"]) assert.ok(CHALLENGE_KINDS[k], k);
|
||||
const base = (buildings: Record<string, number>): BaseState => ({
|
||||
resources: { stahl: 1000, treibstoff: 1000, elektronik: 500, proviant: 1000 }, resUpdatedAt: 0, buildings, units: {},
|
||||
unitsAway: {}, defenses: {}, buildQueue: [], trainingQueue: [], versorgungsmangel: false, powerStored: 0,
|
||||
protection: { createdAtMs: 0, nightShieldStartHour: null, tzOffsetMinutes: 0, nightShieldSuspendedUntilMs: 0, defeatShieldUntilMs: 0 },
|
||||
} as BaseState);
|
||||
const kindsOf = (b: BaseState, others: boolean) => {
|
||||
const c = poolContext(b, { others, raidsPossible: true });
|
||||
const seen = new Set<string>();
|
||||
for (let i = 0; i < 500; i++) for (const d of drawDay(c, `p|${i}`)) seen.add(d.kind);
|
||||
return seen;
|
||||
};
|
||||
const none = kindsOf(base({ kommandozentrale: 3 }), true);
|
||||
for (const k of ["speicherwerk", "stromspeicher", "sturmfahrt", "erkundung"]) assert.ok(!none.has(k), `${k} ohne Gebäude`);
|
||||
const all = kindsOf(base({ kommandozentrale: 3, speicherwerk: 2, kraftwerk: 2, werft: 2, nachrichtendienst: 1 }), true);
|
||||
for (const k of ["speicherwerk", "stromspeicher", "sturmfahrt", "erkundung"]) assert.ok(all.has(k), `${k} mit Gebäude`);
|
||||
assert.ok(!kindsOf(base({ nachrichtendienst: 1 }), false).has("erkundung"), "ohne Ziel keine Erkundung");
|
||||
|
||||
// Sturmfahrt: Aufklärung mit Sturm auf der Route; Speicherwerk-Ausbau aus dem Zustand.
|
||||
const p = await newPlayer("Kapitaen", 70);
|
||||
await patchBase(p.baseId, (s) => { s.units = { korvette: 2 }; s.resources = { ...rich }; s.buildings.speicherwerk = 1; });
|
||||
await quiet();
|
||||
await setDaily(p.playerId, [{ kind: "speicherwerk", target: 2 }, { kind: "sturmfahrt", target: 1 }]);
|
||||
const nest = (await db.select().from(tables.nest))[0];
|
||||
const m = await launchMission(engine, p.playerId, key(), { type: "aufklaerung", units: { korvette: 1 }, col: nest.col, row: nest.row });
|
||||
assert.equal(m.ok, true, JSON.stringify(m));
|
||||
const id = (m as { missionId: number }).missionId;
|
||||
const plan = (await missionRow(id)).plan as Mission;
|
||||
await db.update(tables.mission).set({ plan: { ...plan, weather: { avgWind: 0.9, storminess: 0.5, shipFactor: 1.15 } } }).where(eq(tables.mission.id, id));
|
||||
await arriveNow(id);
|
||||
assert.ok((await dailyOf(p.playerId, "sturmfahrt")).completedAt, "Mission trotz Sturm");
|
||||
await patchBase(p.baseId, (s) => { s.buildings.speicherwerk = 2; });
|
||||
const v = await dailyView(engine, p.playerId);
|
||||
assert.ok(v.challenges.find((c) => c.kind === "speicherwerk")!.progress >= 2, "Speicherwerk aus dem Zustand");
|
||||
});
|
||||
|
||||
test("Belagerung und Admin-Statistik rechnen die Produktion mit Modifikatoren", async () => {
|
||||
const a = await newPlayer("Belagert", 120);
|
||||
await patchBase(a.baseId, (s) => {
|
||||
s.buildings.stahlwerk = 8; s.buildings.kraftwerk = 10; s.buildings.lagerkomplex = 10; s.buildings.hafenkommandantur = 6;
|
||||
s.resources = { stahl: 100, treibstoff: 50000, elektronik: 100, proviant: 50000 };
|
||||
});
|
||||
await quiet();
|
||||
const plain = (await adminStats(db, 7)).flow.productionPerHour.stahl ?? 0;
|
||||
const off = registerModifierSource((_db, playerId) => (playerId === a.playerId ? { production: { stahl: 2 } } : {}), "test", "Test");
|
||||
try {
|
||||
const boosted = (await adminStats(db, 7)).flow.productionPerHour.stahl ?? 0;
|
||||
const own = productionRates(settle(await stateOf(a.baseId), Date.now(), balance), balance).buildingPerHour.stahl ?? 0;
|
||||
assert.ok(own > 0);
|
||||
assert.ok(Math.abs(boosted - plain - own) < 2, `Admin-Statistik mit Modifikator: ${plain} → ${boosted} (+${own})`);
|
||||
|
||||
const id = await spawn("belagerung", a.baseId);
|
||||
const [e] = await db.select().from(tables.worldEvent).where(eq(tables.worldEvent.id, id));
|
||||
const before = await stateOf(a.baseId);
|
||||
const tick = e.startsAt.getTime() + worldEventsBalance(balance).belagerung.tickMinutes * 60000;
|
||||
const mods = await modifiersFor(db, a.playerId, { state: before, nowMs: tick });
|
||||
assert.equal(mods.production?.stahl, 2);
|
||||
await processDue(engine, tick + 10);
|
||||
const after = await stateOf(a.baseId);
|
||||
const expected = settle(before, tick, balance, mods);
|
||||
const perHour = productionRates(expected, balance, mods).buildingPerHour.stahl!;
|
||||
const want = expected.resources.stahl - perHour * 0.3 * ((tick - e.startsAt.getTime()) / HOUR);
|
||||
assert.ok(Math.abs(after.resources.stahl - want) < 0.01, `${after.resources.stahl} ≈ ${want}`);
|
||||
await db.update(tables.worldEvent).set({ status: "ended", outcome: "test" }).where(eq(tables.worldEvent.id, id));
|
||||
} finally {
|
||||
off();
|
||||
}
|
||||
});
|
||||
|
||||
test("Saisonende: Allianzwertung gespeichert, in der Ruhmeshalle und in der Nachricht", async () => {
|
||||
const p1 = await newPlayer("Ally1", 140);
|
||||
const p2 = await newPlayer("Ally2", 144);
|
||||
const p3 = await newPlayer("Solo", 148);
|
||||
await patchBase(p1.baseId, (s) => { s.buildings.stahlwerk = 6; });
|
||||
const [al] = await db.insert(tables.alliance).values({ name: "Nordbund", tag: "NB" }).returning();
|
||||
const [al2] = await db.insert(tables.alliance).values({ name: "Südwacht", tag: "SW" }).returning();
|
||||
await db.insert(tables.allianceMember).values([
|
||||
{ playerId: p1.playerId, allianceId: al.id, role: "fuehrung" },
|
||||
{ playerId: p2.playerId, allianceId: al.id, role: "mitglied" },
|
||||
{ playerId: p3.playerId, allianceId: al2.id, role: "fuehrung" },
|
||||
]);
|
||||
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()));
|
||||
const res = await db.select().from(tables.seasonResult).where(eq(tables.seasonResult.seasonId, season.id));
|
||||
const total = (id: number) => res.find((r) => r.playerId === id)?.total ?? 0;
|
||||
const rows = await db.select().from(tables.seasonAllianceResult).where(eq(tables.seasonAllianceResult.seasonId, season.id));
|
||||
assert.equal(rows.length, 2);
|
||||
const nb = rows.find((r) => r.tag === "NB")!;
|
||||
assert.equal(nb.total, total(p1.playerId) + total(p2.playerId));
|
||||
assert.equal(nb.members, 2);
|
||||
assert.equal(nb.rank, 1, "Nordbund vorn");
|
||||
assert.equal(rows.find((r) => r.tag === "SW")!.total, total(p3.playerId));
|
||||
const hall = await hallOfFame(db, p2.playerId);
|
||||
const h = hall.find((x) => x.number === season.number)!;
|
||||
assert.deepEqual(h.alliances.map((x) => x.tag), ["NB", "SW"]);
|
||||
assert.equal(h.alliances[0].own, true);
|
||||
assert.equal(h.alliances[1].own, false);
|
||||
const [msg] = await db.select().from(tables.message).where(and(eq(tables.message.toPlayerId, p2.playerId), sql`${tables.message.subject} like ${`Saison ${season.number}:%`}`));
|
||||
assert.match(msg.body, /Deine Allianz \[NB\] Nordbund: Platz 1 von 2/);
|
||||
});
|
||||
@@ -405,6 +405,7 @@ export interface Mission {
|
||||
returnAtMs: number;
|
||||
recalledAtMs?: number; // Rückruf auf der Hinfahrt; fehlt ohne Rückruf
|
||||
warningFactor?: number; // Tarnung des Angreifers: Faktor auf die Vorwarnzeit des Ziels (fehlt = 1)
|
||||
detectedAtMs?: number; // vom Radar des Ziels erkannt (Server); einmal erkannt bleibt erkannt
|
||||
weather?: { avgWind: number; storminess: number; shipFactor: number }; // Wetter bei Abfahrt (v1.6)
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user