diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..32c0de0 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,9 @@ +node_modules +**/node_modules +dist +apps/web/dist +.git +.env +backups +*.tar.gz +*.log diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..96f5095 --- /dev/null +++ b/.env.example @@ -0,0 +1,9 @@ +# Kopieren nach .env und anpassen. +TIDEFRONT_PORT=8080 +POSTGRES_PASSWORD=bitte-ein-langes-zufallspasswort +# Einladungscodes, Komma-getrennt; optional :Anzahl Nutzungen (Vorgabe 1). Wird bei jedem Start ergänzt. +INVITE_CODES=FREUNDE2026:10 +BACKUP_HOUR=4 +BACKUP_KEEP_DAYS=14 +BACKUP_DIR=./backups +TZ=Europe/Berlin diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..5e9271f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,18 @@ +# Ein Image für api, worker und migrate; die Oberfläche liegt mit im Image und wird von api ausgeliefert. +FROM node:22-alpine AS build +WORKDIR /app +COPY . . +RUN npm ci --no-audit --no-fund +RUN npm test && npm run build + +FROM node:22-alpine +WORKDIR /app +ENV NODE_ENV=production \ + PORT=8080 \ + MIGRATIONS_DIR=/app/server/migrations \ + WEB_DIR=/app/web +COPY --from=build /app/dist/server ./server +COPY --from=build /app/apps/web/dist ./web +USER node +EXPOSE 8080 +CMD ["node", "--enable-source-maps", "server/api.mjs"] diff --git a/README.md b/README.md index 2333063..6a8a982 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,67 @@ # TIDEFRONT -Strategie-Browserspiel auf der Weltkarte mit Marine, Bodentruppen und Luftwaffe. Hobbyprojekt für den Freundeskreis, Handy zuerst, Betrieb per Docker Compose. - -Stand: Meilenstein 1 in Arbeit. Bisher vorhanden sind die Regel-Spezifikation, die Balance-Daten und der Regelkern. +Strategie-Browserspiel auf der Weltkarte mit Marine, Bodentruppen und Luftwaffe. Hobbyprojekt für den Freundeskreis, +Handy zuerst, Betrieb per Docker Compose. Schauplatz: Nordatlantik mit Mittelmeer als Hexraster. - `docs/REGELN.md` – verbindliche Spielregeln für Meilenstein 1 +- `docs/BAUAUFTRAG.md` – Bauauftrag und Stand der Pakete - `packages/balance/v1/balance.json` – alle Zahlen des Spiels - `packages/game-core` – Spielregeln und Börsenkern als reine Funktionen, ohne Fremdpakete +- `packages/world` – Hexraster, Küsten, Nestplätze, Handelshäfen (rein, von Server und Oberfläche genutzt) +- `packages/db` – Datenbankschema (Drizzle) und Migrationen +- `packages/engine` – Server-Logik: Ereignis-Queue, Befehle, Börse, Prüflauf +- `apps/api` – Fastify, tRPC, WebSocket, Auslieferung der Oberfläche +- `apps/worker` – verarbeitet fällige Ereignisse, Prüflauf, Aufräumen +- `apps/web` – Oberfläche (React, Vite, Tailwind, TanStack Query, PixiJS) als PWA -Tests (Node 22.18 oder neuer, keine Installation nötig): +## Starten (Raspberry Pi oder jeder Rechner mit Docker) - npm test +Voraussetzung: Docker mit Compose-Plugin, 64-Bit-System (arm64 oder amd64). + + git clone https://github.com/db9979/tidefront.git + cd tidefront + cp .env.example .env + # in .env: POSTGRES_PASSWORD auf ein langes Zufallspasswort setzen, INVITE_CODES festlegen + docker compose up -d + +Der erste Start baut das Image (auf dem Pi einige Minuten). Danach läuft das Spiel auf `http://:8080`. +Der vorhandene Proxy leitet HTTPS auf diesen Port weiter; WebSocket läuft unter `/ws` über denselben Port, +der Proxy muss also `Upgrade`-Header durchreichen. Postgres und Valkey sind nur im Container-Netz erreichbar. + +Dienste: `api` (Port 8080), `worker`, `migrate` (läuft vor jedem Start einmal, legt Schema, Nester, Markt und +Einladungscodes an), `postgres`, `valkey`, `backup`. Zustand: `docker compose ps`, Protokolle: `docker compose logs -f api worker`. + +Mitspieler einladen: Code in `INVITE_CODES` eintragen (z. B. `FREUNDE2026:10` für zehn Anmeldungen), dann +`docker compose up -d` – `migrate` ergänzt neue Codes, ohne bestehende zu verringern. + +Aktualisieren: + + git pull + docker compose up -d --build + +## Sicherung und Wiederherstellung + +Der Dienst `backup` sichert täglich um `BACKUP_HOUR` Uhr nach `./backups` (Vorgabe, änderbar über `BACKUP_DIR`) +und hält `BACKUP_KEEP_DAYS` Tage vor. Beim ersten Start wird sofort gesichert. + + docker compose exec backup sh /scripts/backup.sh once # jetzt sichern + docker compose exec backup sh /scripts/backup.sh restore-test /backups/.dump # Probe in eigener DB + +Ernstfall (Spielstand aus einer Sicherung zurückholen): + + docker compose stop api worker + docker compose exec backup sh /scripts/backup.sh restore /backups/.dump + docker compose start api worker + +## Entwickeln + +Node 22.18 oder neuer. + + npm install + npm test # Regelkern und Börse (ohne Datenbank) + npm run typecheck + npm run sim # Balance-Simulation + TEST_DATABASE_URL=postgres://... npm run test:server # Server gegen ein leeres PostgreSQL (wird geleert!) + +Lokal mit Postgres und Valkey: `npm run dev:api`, `npm run dev:worker`, `npm run dev:web` (Vite leitet `/trpc` und +`/ws` an den API-Port weiter). Schemaänderungen: `packages/db/src/schema.ts` ändern, dann `npm run db:generate`. diff --git a/apps/web/index.html b/apps/web/index.html new file mode 100644 index 0000000..8f33a93 --- /dev/null +++ b/apps/web/index.html @@ -0,0 +1,18 @@ + + + + + + + + + + + + TIDEFRONT + + +
+ + + diff --git a/apps/web/public/icon-192.png b/apps/web/public/icon-192.png new file mode 100644 index 0000000..4a639e6 Binary files /dev/null and b/apps/web/public/icon-192.png differ diff --git a/apps/web/public/icon-512.png b/apps/web/public/icon-512.png new file mode 100644 index 0000000..628e372 Binary files /dev/null and b/apps/web/public/icon-512.png differ diff --git a/apps/web/public/icon.svg b/apps/web/public/icon.svg new file mode 100644 index 0000000..6e43c22 --- /dev/null +++ b/apps/web/public/icon.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/apps/web/public/manifest.webmanifest b/apps/web/public/manifest.webmanifest new file mode 100644 index 0000000..3ca7f12 --- /dev/null +++ b/apps/web/public/manifest.webmanifest @@ -0,0 +1,17 @@ +{ + "name": "TIDEFRONT", + "short_name": "TIDEFRONT", + "description": "Strategie auf dem Nordatlantik", + "lang": "de", + "start_url": "/", + "scope": "/", + "display": "standalone", + "orientation": "portrait", + "background_color": "#0b1726", + "theme_color": "#0b1726", + "icons": [ + { "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" }, + { "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" }, + { "src": "/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" } + ] +} diff --git a/apps/web/public/sw.js b/apps/web/public/sw.js new file mode 100644 index 0000000..6f06176 --- /dev/null +++ b/apps/web/public/sw.js @@ -0,0 +1,46 @@ +// Einfacher Service Worker: App-Shell cachen, Navigation zuerst aus dem Netz, API nie cachen. +const CACHE = "tidefront-v1"; +const SHELL = ["/", "/index.html", "/manifest.webmanifest", "/icon.svg"]; + +self.addEventListener("install", (e) => { + e.waitUntil(caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting())); +}); + +self.addEventListener("activate", (e) => { + e.waitUntil( + caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))).then(() => self.clients.claim()), + ); +}); + +self.addEventListener("fetch", (e) => { + const url = new URL(e.request.url); + if (e.request.method !== "GET" || url.origin !== location.origin) return; + if (url.pathname.startsWith("/trpc") || url.pathname.startsWith("/ws") || url.pathname.startsWith("/healthz")) return; + if (e.request.mode === "navigate") { + e.respondWith( + fetch(e.request) + .then((res) => { + const copy = res.clone(); + caches.open(CACHE).then((c) => c.put("/index.html", copy)); + return res; + }) + .catch(() => caches.match("/index.html")), + ); + return; + } + if (url.pathname.startsWith("/assets/") || SHELL.includes(url.pathname) || url.pathname.endsWith(".png")) { + e.respondWith( + caches.match(e.request).then( + (hit) => + hit ?? + fetch(e.request).then((res) => { + if (res.ok) { + const copy = res.clone(); + caches.open(CACHE).then((c) => c.put(e.request, copy)); + } + return res; + }), + ), + ); + } +}); diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx new file mode 100644 index 0000000..f694e8f --- /dev/null +++ b/apps/web/src/App.tsx @@ -0,0 +1,85 @@ +import { useState } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { trpc, trpcClient, queryClient } from "./lib/trpc.ts"; +import { useLive } from "./lib/live.ts"; +import { Loading } from "./ui.tsx"; +import { AuthScreen } from "./screens/Auth.tsx"; +import { ChooseBase } from "./screens/ChooseBase.tsx"; +import { BaseScreen } from "./screens/Base.tsx"; +import { MapScreen } from "./screens/MapScreen.tsx"; +import { TroopsScreen } from "./screens/Troops.tsx"; +import { MissionPlan } from "./screens/MissionPlan.tsx"; +import { ReportsScreen } from "./screens/Reports.tsx"; +import { MarketScreen } from "./screens/Market.tsx"; + +export type Tab = "basis" | "karte" | "truppen" | "berichte" | "boerse"; +export interface Target { col: number; row: number } + +const TABS: { id: Tab; label: string; icon: string }[] = [ + { id: "basis", label: "Basis", icon: "⚓" }, + { id: "karte", label: "Karte", icon: "🗺" }, + { id: "truppen", label: "Truppen", icon: "🎖" }, + { id: "berichte", label: "Berichte", icon: "📜" }, + { id: "boerse", label: "Börse", icon: "⚖" }, +]; + +export function App() { + const me = useQuery(trpc.auth.me.queryOptions()); + const loggedIn = !!me.data?.player; + const base = useQuery({ ...trpc.base.get.queryOptions(), enabled: loggedIn, refetchInterval: 30000 }); + useLive(loggedIn); + const [tab, setTab] = useState("basis"); + const [plan, setPlan] = useState<{ target: Target | null } | null>(null); + const [mapFocus, setMapFocus] = useState(null); + + if (me.isLoading) return ; + if (!loggedIn) return ; + if (base.isLoading || !base.data) return ; + if (!base.data.base) return ; + + const logout = async () => { + await trpcClient.auth.logout.mutate(); + queryClient.clear(); + await me.refetch(); + }; + + const openPlan = (target: Target | null) => setPlan({ target }); + const content = plan ? ( + setPlan(null)} + onPickOnMap={() => { setPlan(null); setTab("karte"); }} + /> + ) : tab === "basis" ? ( + + ) : tab === "karte" ? ( + + ) : tab === "truppen" ? ( + openPlan(null)} onShowOnMap={(t) => { setMapFocus(t); setTab("karte"); }} /> + ) : tab === "berichte" ? ( + + ) : ( + + ); + + return ( +
+
{content}
+ +
+ ); +} diff --git a/apps/web/src/lib/command.ts b/apps/web/src/lib/command.ts new file mode 100644 index 0000000..f4f4451 --- /dev/null +++ b/apps/web/src/lib/command.ts @@ -0,0 +1,33 @@ +// Befehle mit Idempotenz-Schlüssel: frischer Schlüssel je Absicht, nach Netzfehler derselbe. +import { useRef, useState } from "react"; +import { queryClient } from "./trpc.ts"; +import { errorText } from "./names.ts"; + +type Res = { ok: boolean; code?: string }; + +export function useCommand

(call: (input: P) => Promise, invalidate: () => unknown[]) { + const pending = useRef<{ sig: string; key: string } | null>(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + async function run(input: Omit): Promise { + const sig = JSON.stringify(input); + if (!pending.current || pending.current.sig !== sig) pending.current = { sig, key: crypto.randomUUID() }; + setBusy(true); + setError(null); + try { + const out = await call({ ...input, key: pending.current.key } as P); + pending.current = null; + if (!out.ok) setError(errorText(out.code ?? "?")); + for (const k of invalidate()) await queryClient.invalidateQueries({ queryKey: k as readonly unknown[] }); + return out; + } catch { + // Netzfehler: Schlüssel behalten, damit eine Wiederholung nicht doppelt wirkt. + setError(errorText("network")); + return null; + } finally { + setBusy(false); + } + } + return { run, busy, error, setError }; +} diff --git a/apps/web/src/lib/live.ts b/apps/web/src/lib/live.ts new file mode 100644 index 0000000..af8b14d --- /dev/null +++ b/apps/web/src/lib/live.ts @@ -0,0 +1,51 @@ +// WebSocket /ws: Änderungsmeldungen invalidieren passende Abfragen; Neuverbindung mit Rückstau. +import { useEffect } from "react"; +import { queryClient, trpc } from "./trpc.ts"; +import { noteServerTime } from "./time.ts"; + +const FILTERS: Record { queryKey: readonly unknown[] }[]> = { + base: () => [trpc.base.pathFilter()], + missions: () => [trpc.base.pathFilter()], + reports: () => [trpc.report.pathFilter(), trpc.base.pathFilter()], + market: () => [trpc.market.pathFilter(), trpc.base.pathFilter()], + map: () => [trpc.world.pathFilter()], +}; + +export function useLive(enabled: boolean): void { + useEffect(() => { + if (!enabled) return; + let ws: WebSocket | null = null; + let stopped = false; + let delay = 1000; + let timer: ReturnType | undefined; + const connect = () => { + const proto = location.protocol === "https:" ? "wss:" : "ws:"; + ws = new WebSocket(`${proto}//${location.host}/ws`); + ws.onopen = () => { + delay = 1000; + // Nach Neuverbindung alles frisch holen (Meldungen könnten verpasst sein). + void queryClient.invalidateQueries(); + }; + ws.onmessage = (ev) => { + try { + const msg = JSON.parse(String(ev.data)) as { kind: string; serverNow?: number }; + if (typeof msg.serverNow === "number") noteServerTime(msg.serverNow); + for (const f of FILTERS[msg.kind]?.() ?? []) void queryClient.invalidateQueries(f); + } catch { + /* ignorieren */ + } + }; + ws.onclose = () => { + if (stopped) return; + timer = setTimeout(connect, delay); + delay = Math.min(30000, delay * 2); + }; + }; + connect(); + return () => { + stopped = true; + clearTimeout(timer); + ws?.close(); + }; + }, [enabled]); +} diff --git a/apps/web/src/lib/names.ts b/apps/web/src/lib/names.ts new file mode 100644 index 0000000..344e7fa --- /dev/null +++ b/apps/web/src/lib/names.ts @@ -0,0 +1,87 @@ +// Deutsche Namen und Meldungen. + +const NAMES: Record = { + kommandozentrale: "Kommandozentrale", stahlwerk: "Stahlwerk", raffinerie: "Raffinerie", chipfabrik: "Chipfabrik", + versorgungshof: "Versorgungshof", kraftwerk: "Kraftwerk", lagerkomplex: "Lagerkomplex", tiefbunker: "Tiefbunker", + werft: "Werft", kaserne: "Kaserne", flugfeld: "Flugfeld", radarstation: "Radarstation", hafenkommandantur: "Hafenkommandantur", + korvette: "Korvette", zerstoerer: "Zerstörer", landungsschiff: "Landungsschiff", schuetzen: "Schützen", pioniere: "Pioniere", + kampfpanzer: "Kampfpanzer", abfangjaeger: "Abfangjäger", jagdbomber: "Jagdbomber", aufklaerungsdrohne: "Aufklärungsdrohne", + schnellboot: "Schnellboot", piratenmiliz: "Piratenmiliz", kuestenbatterie: "Küstenbatterie", flakstellung: "Flakstellung", + bunkerlinie: "Bunkerlinie", minensperre: "Minensperre", anlagen: "Anlagen", + stahl: "Stahl", treibstoff: "Treibstoff", elektronik: "Elektronik", proviant: "Proviant", credits: "Kredite", + ueberfall: "Überfall", aufklaerung: "Aufklärung", transport: "Transport", kartell: "Kartell-Überfall", + luftkampf: "Luftkampf", luftschlag: "Luftschlag", seegefecht: "Seegefecht", landung: "Landung", + anfaengerschutz: "Anfängerschutz", niederlage: "Schutz nach Niederlage", nachtschild: "Nachtschild", +}; + +/** Name aus einer ID; unbekannte IDs werden lesbar gemacht (ae → ä usw.). */ +export function label(id: string): string { + if (NAMES[id]) return NAMES[id]; + const s = id.replace(/ae/g, "ä").replace(/oe/g, "ö").replace(/ue/g, "ü").replace(/_/g, " "); + return s.charAt(0).toUpperCase() + s.slice(1); +} + +export const RES_ICON: Record = { stahl: "⛓", treibstoff: "🛢", elektronik: "🔌", proviant: "🥫" }; + +const ERRORS: Record = { + insufficient_resources: "Nicht genug Ressourcen.", + queue_full: "Es läuft schon ein Ausbau.", + queue_busy: "Dieses Gebäude bildet schon aus.", + max_level: "Höchststufe erreicht.", + command_cap: "Erst die Kommandozentrale ausbauen.", + building_required: "Dafür fehlt das passende Gebäude.", + supply_shortage: "Versorgungsmangel: keine Ausbildung möglich.", + no_aircraft_slots: "Keine freien Stellplätze auf dem Flugfeld.", + troop_capacity: "Zu wenig Platz auf den Landungsschiffen.", + command_points: "Der Verband kostet zu viele Kommandopunkte.", + fuel: "Nicht genug Treibstoff.", + out_of_range: "Ein Flugzeugtyp erreicht das Ziel nicht.", + no_mission_slot: "Alle Missionsplätze sind belegt.", + target_protected: "Das Ziel steht unter Schutz.", + nest_empty: "Das Nest ist verlassen.", + no_target: "Auf diesem Feld gibt es kein Ziel.", + own_base: "Das ist der eigene Stützpunkt.", + transport_needs_base: "Transporte gehen nur an Stützpunkte.", + empty_fleet: "Keine Einheiten gewählt.", + units_unavailable: "So viele Einheiten sind nicht daheim.", + no_carrier: "Der Verband braucht Schiffe oder Flugzeuge.", + cargo_capacity: "Die Ladung übersteigt die Ladekapazität.", + cargo_not_allowed: "Ladung nur beim Transport.", + bad_cargo: "Ungültige Ladung.", + bad_type: "Unbekannter Missionstyp.", + bad_count: "Ungültige Anzahl.", + unknown_unit: "Unbekannte Einheit.", + unknown_building: "Unbekanntes Gebäude.", + no_order: "Kein laufender Auftrag.", + already_finished: "Der Auftrag ist schon fertig.", + locked: "Die Börse öffnet ab Hafenkommandantur Stufe 3.", + halted: "Handel mit dieser Ressource ist pausiert.", + bad_qty: "Ungültige Menge.", + impact: "Die Menge bewegt den Kurs zu stark. Kleinere Menge wählen.", + rate: "Zu viele Geschäfte in kurzer Zeit.", + daily_limit: "Tageslimit für diese Ressource erreicht.", + under_attack: "Ein Angriff ist im Anmarsch: Verkäufe gesperrt.", + credit_limit: "Das Kreditlimit wäre überschritten.", + funds: "Bestand oder Kredite reichen nicht.", + slippage: "Der Kurs hat sich bewegt. Bitte neu prüfen.", + price_bounds: "Der Kurs würde die erlaubten Grenzen verlassen.", + band: "Kursband verletzt: Handel für eine Weile pausiert.", + invite_invalid: "Einladungscode ungültig oder verbraucht.", + name_taken: "Der Name ist schon vergeben.", + bad_login: "Name oder Passwort falsch.", + not_coast: "Nur Küstenfelder sind erlaubt.", + field_taken: "Das Feld ist schon belegt.", + has_base: "Du hast schon einen Stützpunkt.", + no_base: "Noch kein Stützpunkt.", + rate_limited: "Zu viele Versuche. Bitte kurz warten.", + network: "Keine Verbindung zum Server. Bitte erneut versuchen.", +}; + +export function errorText(code: string): string { + if (code === "rate") return "Zu viele Versuche. Bitte kurz warten."; + return ERRORS[code] ?? `Abgelehnt (${code}).`; +} + +export function fmtNum(n: number, digits = 0): string { + return n.toLocaleString("de-DE", { maximumFractionDigits: digits, minimumFractionDigits: digits }); +} diff --git a/apps/web/src/lib/time.ts b/apps/web/src/lib/time.ts new file mode 100644 index 0000000..ffb3cac --- /dev/null +++ b/apps/web/src/lib/time.ts @@ -0,0 +1,43 @@ +import { useEffect, useState } from "react"; + +let offsetMs = 0; + +/** Offset = serverNow − Date.now() beim Empfang. */ +export function noteServerTime(serverNow: number): void { + offsetMs = serverNow - Date.now(); +} + +export function serverNow(): number { + return Date.now() + offsetMs; +} + +/** Tick einmal je Sekunde; liefert die aktuelle Serverzeit. */ +export function useNow(intervalMs = 1000): number { + const [now, setNow] = useState(serverNow()); + useEffect(() => { + const t = setInterval(() => setNow(serverNow()), intervalMs); + return () => clearInterval(t); + }, [intervalMs]); + return now; +} + +export function fmtDuration(ms: number): string { + if (ms <= 0) return "gleich"; + const s = Math.ceil(ms / 1000); + const d = Math.floor(s / 86400); + const h = Math.floor((s % 86400) / 3600); + const m = Math.floor((s % 3600) / 60); + const sec = s % 60; + if (d > 0) return `${d} T ${h} h`; + if (h > 0) return `${h} h ${String(m).padStart(2, "0")} min`; + if (m > 0) return `${m}:${String(sec).padStart(2, "0")} min`; + return `${sec} s`; +} + +export function fmtSeconds(sec: number): string { + return fmtDuration(sec * 1000); +} + +export function fmtTime(ms: number): string { + return new Date(ms - offsetMs).toLocaleString("de-DE", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" }); +} diff --git a/apps/web/src/lib/trpc.ts b/apps/web/src/lib/trpc.ts new file mode 100644 index 0000000..e7690e7 --- /dev/null +++ b/apps/web/src/lib/trpc.ts @@ -0,0 +1,37 @@ +import { QueryClient } from "@tanstack/react-query"; +import { createTRPCClient, httpBatchLink, TRPCClientError } from "@trpc/client"; +import { createTRPCOptionsProxy } from "@trpc/tanstack-react-query"; +import type { inferRouterOutputs } from "@trpc/server"; +import type { AppRouter } from "@tidefront/api/router"; +import { noteServerTime } from "./time.ts"; + +export const queryClient = new QueryClient({ + defaultOptions: { + queries: { + staleTime: 5000, + retry: (n, err) => !(err instanceof TRPCClientError && err.data?.code === "UNAUTHORIZED") && n < 2, + }, + }, +}); + +export const trpcClient = createTRPCClient({ + links: [ + httpBatchLink({ + url: "/trpc", + fetch: (url, opts) => fetch(url, { ...(opts as RequestInit), credentials: "same-origin" }), + }), + ], +}); + +export const trpc = createTRPCOptionsProxy({ client: trpcClient, queryClient }); + +export type Outputs = inferRouterOutputs; +export type BaseData = NonNullable; +export type MapData = Outputs["world"]["map"]; +export type Balance = Outputs["meta"]["balance"]; + +/** Antworten mit serverNow aktualisieren den Zeitversatz. */ +queryClient.getQueryCache().subscribe((e) => { + const data = e.query.state.data as { serverNow?: number } | undefined; + if (e.type === "updated" && data && typeof data.serverNow === "number") noteServerTime(data.serverNow); +}); diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx new file mode 100644 index 0000000..4b07095 --- /dev/null +++ b/apps/web/src/main.tsx @@ -0,0 +1,18 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { queryClient } from "./lib/trpc.ts"; +import { App } from "./App.tsx"; +import "./styles.css"; + +createRoot(document.getElementById("root")!).render( + + + + + , +); + +if ("serviceWorker" in navigator && import.meta.env.PROD) { + window.addEventListener("load", () => void navigator.serviceWorker.register("/sw.js")); +} diff --git a/apps/web/src/screens/Auth.tsx b/apps/web/src/screens/Auth.tsx new file mode 100644 index 0000000..f19e4a4 --- /dev/null +++ b/apps/web/src/screens/Auth.tsx @@ -0,0 +1,62 @@ +import { useState } from "react"; +import { trpc, trpcClient, queryClient } from "../lib/trpc.ts"; +import { errorText } from "../lib/names.ts"; +import { Button, ErrorLine } from "../ui.tsx"; + +export function AuthScreen() { + const [mode, setMode] = useState<"login" | "register">("login"); + const [name, setName] = useState(""); + const [password, setPassword] = useState(""); + const [invite, setInvite] = useState(""); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + const submit = async (e: React.FormEvent) => { + e.preventDefault(); + setBusy(true); + setError(null); + try { + const r = + mode === "login" + ? await trpcClient.auth.login.mutate({ name, password }) + : await trpcClient.auth.register.mutate({ name, password, inviteCode: invite }); + if (!r.ok) setError(errorText(r.code)); + else await queryClient.invalidateQueries(trpc.auth.pathFilter()); + } catch (err) { + const msg = String((err as Error).message ?? ""); + setError(msg.includes("password") || msg.includes("name") ? "Name (3–24 Zeichen) und Passwort (mind. 8 Zeichen) prüfen." : errorText("network")); + } finally { + setBusy(false); + } + }; + + const field = "w-full h-12 rounded-lg bg-navy-950 border border-navy-600 px-3 mb-3"; + return ( +

+ +

TIDEFRONT

+

Nordatlantik · Mittelmeer

+
+ {(["login", "register"] as const).map((m) => ( + + ))} +
+
+ + setName(e.target.value)} autoComplete="username" required /> + + setPassword(e.target.value)} autoComplete={mode === "login" ? "current-password" : "new-password"} required /> + {mode === "register" && ( + <> + + setInvite(e.target.value)} autoCapitalize="characters" required /> + + )} + + + +
+ ); +} diff --git a/apps/web/src/screens/Base.tsx b/apps/web/src/screens/Base.tsx new file mode 100644 index 0000000..823bfac --- /dev/null +++ b/apps/web/src/screens/Base.tsx @@ -0,0 +1,179 @@ +import { useState } from "react"; +import { trpc, trpcClient, type BaseData } from "../lib/trpc.ts"; +import { useCommand } from "../lib/command.ts"; +import { RES_ICON, fmtNum, label } from "../lib/names.ts"; +import { fmtDuration, fmtSeconds, fmtTime, useNow } from "../lib/time.ts"; +import { Button, Card, Cost, CountsLine, ErrorLine } from "../ui.tsx"; + +const INFO: Record = { + kommandozentrale: "Kommandopunkte, Deckel für alle Gebäude", + stahlwerk: "Stahl je Stunde", + raffinerie: "Treibstoff je Stunde", + chipfabrik: "Elektronik je Stunde", + versorgungshof: "Proviant je Stunde", + kraftwerk: "Strom für die Produktion", + lagerkomplex: "Lagerkapazität", + tiefbunker: "Schutz vor Plünderung", + werft: "Schiffe bauen", + kaserne: "Bodentruppen ausbilden", + flugfeld: "Flugzeuge und Stellplätze", + radarstation: "Vorwarnzeit bei Angriffen", + hafenkommandantur: "Missionsplätze, Börse ab Stufe 3", +}; + +const invalidateBase = () => [trpc.base.pathFilter().queryKey]; + +const ORDER = ["stahl", "treibstoff", "elektronik", "proviant"]; + +export function BaseScreen({ base, asOf, playerName, onLogout }: { base: BaseData; asOf: number; playerName: string; onLogout: () => void }) { + const now = useNow(); + const up = useCommand((i: { key: string; buildingId: string }) => trpcClient.base.upgrade.mutate(i), invalidateBase); + const cancel = useCommand((i: { key: string }) => trpcClient.base.cancelUpgrade.mutate(i), invalidateBase); + const order = base.buildQueue[0]; + const busy = base.buildQueue.length > 0; + + return ( +
+
+
+

{base.name}

+

Kommandant {playerName} · Feld {base.col}/{base.row}

+
+ +
+ + {base.incoming.filter((i) => i.type !== "transport").map((i) => ( +
+ ⚠ {label(i.type)} im Anmarsch – Ankunft in {fmtDuration(i.arriveAtMs - now)} + {i.units &&
} +
+ ))} + + Lager je {fmtNum(base.capacity)}}> +
+ {ORDER.filter((r) => r in base.resources).map((r) => { + const rate = base.rates[r] ?? 0; + // Im Client fortschreiben: Produktion füllt nur bis zur Kapazität, Bestand nie unter 0. + const raw = base.resources[r]; + const grown = raw + (rate * Math.max(0, now - asOf)) / 3600000; + const v = rate >= 0 ? (raw >= base.capacity ? raw : Math.min(base.capacity, grown)) : Math.max(0, grown); + const full = v >= base.capacity; + return ( +
+
{RES_ICON[r]} {label(r)}
+
{fmtNum(v)}
+
{rate >= 0 ? "+" : ""}{fmtNum(rate)}/h{full ? " · voll" : ""}
+
+ ); + })} +
+
+ ⚡ Strom {fmtNum(base.power.demand)}/{fmtNum(base.power.supply)}{base.power.factor < 1 ? ` – Drosselung auf ${fmtNum(base.power.factor * 100)} %` : ""} + Unterhalt {fmtNum(base.upkeepPerHour, 1)} Proviant/h + Bunkerschutz {fmtNum(base.bunkerProtection)} je Ressource +
+ {base.versorgungsmangel &&

Versorgungsmangel: keine Ausbildung, Angriffswert −20 %.

} + {base.deliveries.length > 0 && ( +
+ {base.deliveries.map((d) =>
Lieferung {fmtNum(d.qty)} {label(d.resource)} in {fmtDuration(d.arriveAtMs - now)}
)} +
+ )} +
+ + + + + {order ? ( +
+
+
{label(order.buildingId)} → Stufe {order.targetLevel}
+
{order.finishesAt <= now ? "wird abgeschlossen …" : `noch ${fmtDuration(order.finishesAt - now)}`}
+ +
+ +
+ ) : ( +

Kein Ausbau. Wähle ein Gebäude.

+ )} + +
+ + + +
    + {base.buildings.map((b) => { + const capped = b.level >= b.maxAllowed; + return ( +
  • +
    +
    {label(b.id)} Stufe {b.level}
    +
    {INFO[b.id]}
    + {b.cost && } + {b.seconds !== null &&
    ⏱ {fmtSeconds(b.seconds)}{capped ? " · erst Kommandozentrale ausbauen" : ""}
    } +
    + +
  • + ); + })} +
+
+ + +
+ Kommandopunkte{fmtNum(base.commandPoints)} + Missionsplätze{base.activeMissions}/{base.missionSlots} + Stellplätze Flugfeld{base.aircraftSlots.used}/{base.aircraftSlots.total} + Radar-Vorwarnzeit{base.radarWarningMinutes} min +
+
+
+ ); +} + +export function Progress({ start, end, now }: { start: number; end: number; now: number }) { + const p = Math.max(0, Math.min(1, (now - start) / Math.max(1, end - start))); + return ( +
+
+
+ ); +} + +function Protection({ base, now }: { base: BaseData; now: number }) { + const p = base.protection; + const [hour, setHour] = useState(p.nightShieldStartHour); + const save = useCommand( + (i: { key: string; startHour: number | null; tzOffsetMinutes: number }) => trpcClient.base.nightShield.mutate(i), + invalidateBase, + ); + const win = p.nightWindow; + return ( + +

+ {p.status ? 🛡 {label(p.status)} aktiv : Kein Schutz aktiv} +

+ {win && ( +

+ {now >= win.startMs && now < win.endMs ? `Nachtschild bis ${fmtTime(win.endMs)}` : `Nächster Nachtschild ${fmtTime(win.startMs)} – ${fmtTime(win.endMs)}`} + {p.nightShieldSuspendedUntilMs > now ? " (durch eigenen Angriff aufgehoben)" : ""} +

+ )} +
+ + +
+ +
+ ); +} diff --git a/apps/web/src/screens/ChooseBase.tsx b/apps/web/src/screens/ChooseBase.tsx new file mode 100644 index 0000000..958c072 --- /dev/null +++ b/apps/web/src/screens/ChooseBase.tsx @@ -0,0 +1,62 @@ +import { useMemo, useState } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { isCoast } from "@tidefront/world"; +import { trpc, trpcClient } from "../lib/trpc.ts"; +import { useCommand } from "../lib/command.ts"; +import { HexMap } from "./HexMap.tsx"; +import { Button, ErrorLine, Loading } from "../ui.tsx"; + +export function ChooseBase() { + const map = useQuery(trpc.world.map.queryOptions()); + const [sel, setSel] = useState<{ col: number; row: number } | null>(null); + const [name, setName] = useState(""); + const [nightHour, setNightHour] = useState(23); + const cmd = useCommand( + (i: { key: string; col: number; row: number; name: string; nightShieldStartHour: number | null; tzOffsetMinutes: number }) => trpcClient.base.choose.mutate(i), + () => [trpc.base.pathFilter().queryKey, trpc.world.pathFilter().queryKey], + ); + const taken = useMemo(() => { + const s = new Set(); + for (const b of map.data?.bases ?? []) s.add(`${b.col},${b.row}`); + for (const n of map.data?.nests ?? []) s.add(`${n.col},${n.row}`); + return s; + }, [map.data]); + if (!map.data) return ; + const free = sel !== null && isCoast(sel.col, sel.row) && !taken.has(`${sel.col},${sel.row}`); + + return ( +
+
+

Wähle ein Küstenfeld für deinen Stützpunkt

+

Hell umrandete Felder sind freie Küste. Ziehen zum Verschieben, zwei Finger zum Zoomen.

+
+
+ +
+
+ {!sel &&

Tippe ein Küstenfeld an.

} + {sel && !free &&

Dieses Feld ist keine freie Küste.

} + {sel && free && ( +
+ setName(e.target.value)} /> + + +
+ )} + +
+
+ ); +} diff --git a/apps/web/src/screens/HexMap.tsx b/apps/web/src/screens/HexMap.tsx new file mode 100644 index 0000000..a474fa4 --- /dev/null +++ b/apps/web/src/screens/HexMap.tsx @@ -0,0 +1,258 @@ +// Hexkarte mit PixiJS: Gelände einmal gezeichnet, Marker bei neuen Daten, Schwenken per Ziehen, +// Zoomen per Zwei-Finger oder Mausrad, Tippen wählt ein Feld. +import { useEffect, useRef, useState } from "react"; +import { Application, Container, Graphics, Text } from "pixi.js"; +import { + COLS, + HEX_SIZE_KM, + ROWS, + hexAtXY, + hexCenterXY, + hexIndex, + inGrid, + terrainMap, +} from "@tidefront/world"; +import type { MapData } from "../lib/trpc.ts"; + +export interface HexMapProps { + data: MapData; + selected: { col: number; row: number } | null; + onSelect: (h: { col: number; row: number }) => void; + selectMode?: boolean; + center?: { col: number; row: number } | null; +} + +const COLOR = { sea: 0x0f2a44, coast: 0x6b7d45, land: 0x2f4a2b, bg: 0x060e18 }; +const MIN_SCALE = 0.04; +const MAX_SCALE = 2.5; + +function hexPoints(cx: number, cy: number, size: number): number[] { + const pts: number[] = []; + for (let i = 0; i < 6; i++) { + const a = ((60 * i - 30) * Math.PI) / 180; + pts.push(cx + size * Math.cos(a), cy + size * Math.sin(a)); + } + return pts; +} + +interface Scene { + app: Application; + world: Container; + markers: Container; + selection: Graphics; +} + +export function HexMap({ data, selected, onSelect, selectMode, center }: HexMapProps) { + const host = useRef(null); + const scene = useRef(null); + const [ready, setReady] = useState(false); + const onSelectRef = useRef(onSelect); + onSelectRef.current = onSelect; + + // Aufbau (einmal) + useEffect(() => { + const el = host.current!; + let destroyed = false; + const app = new Application(); + const cleanups: (() => void)[] = []; + void app + .init({ resizeTo: el, background: COLOR.bg, antialias: true, resolution: Math.min(2, window.devicePixelRatio || 1), autoDensity: true }) + .then(() => { + if (destroyed) { + app.destroy(true); + return; + } + el.appendChild(app.canvas); + app.canvas.style.touchAction = "none"; + app.canvas.style.display = "block"; + const world = new Container(); + app.stage.addChild(world); + const terrain = new Graphics(); + const t = terrainMap(); + for (let row = 0; row < ROWS; row++) { + for (let col = 0; col < COLS; col++) { + const { x, y } = hexCenterXY(col, row); + terrain.poly(hexPoints(x, y, HEX_SIZE_KM * 0.95)).fill({ color: COLOR[t[hexIndex(col, row)]] }); + } + } + world.addChild(terrain); + if (selectMode) { + const ring = new Graphics(); + for (let row = 0; row < ROWS; row++) for (let col = 0; col < COLS; col++) { + if (t[hexIndex(col, row)] !== "coast") continue; + const { x, y } = hexCenterXY(col, row); + ring.poly(hexPoints(x, y, HEX_SIZE_KM * 0.85)).stroke({ color: 0xf2c14e, width: 5, alpha: 0.55 }); + } + world.addChild(ring); + } + const markers = new Container(); + world.addChild(markers); + const selection = new Graphics(); + world.addChild(selection); + scene.current = { app, world, markers, selection }; + cleanups.push(attachGestures(app.canvas, world, (x, y) => { + const h = hexAtXY(x, y); + if (inGrid(h.col, h.row)) onSelectRef.current(h); + })); + setReady(true); + }); + return () => { + destroyed = true; + for (const c of cleanups) c(); + if (scene.current) { + scene.current.app.destroy(true, { children: true }); + scene.current = null; + } + }; + }, [selectMode]); + + // Ausgangsansicht: auf das gewünschte Feld zentrieren + const centerKey = center ? `${center.col},${center.row}` : ""; + useEffect(() => { + const s = scene.current; + if (!ready || !s) return; + const w = s.app.screen.width; + const h = s.app.screen.height; + const target = center ? hexCenterXY(center.col, center.row) : hexCenterXY(Math.floor(COLS / 2), Math.floor(ROWS / 2)); + const scale = center ? 0.35 : Math.max(MIN_SCALE, Math.min(w / (COLS * HEX_SIZE_KM * 1.75), h / (ROWS * HEX_SIZE_KM * 1.5)) * 2.2); + s.world.scale.set(scale); + s.world.position.set(w / 2 - target.x * scale, h / 2 - target.y * scale); + }, [ready, centerKey]); + + // Marker + useEffect(() => { + const s = scene.current; + if (!ready || !s) return; + for (const c of s.markers.removeChildren()) c.destroy(); + const g = new Graphics(); + for (const w of data.wrecks) { + const { x, y } = hexCenterXY(w.col, w.row); + g.poly([x + 22, y - 30, x + 34, y - 18, x + 22, y - 6, x + 10, y - 18]).fill({ color: 0xe8893a }); + } + for (const n of data.nests) { + const { x, y } = hexCenterXY(n.col, n.row); + g.circle(x, y, 26).fill({ color: n.empty ? 0x4b5563 : 0x8e3fb8 }).stroke({ color: 0x0b1726, width: 4 }); + } + for (const b of data.bases) { + const { x, y } = hexCenterXY(b.col, b.row); + g.rect(x - 24, y - 24, 48, 48).fill({ color: b.own ? 0xf2c14e : 0xe5484d }).stroke({ color: 0xffffff, width: 5 }); + } + s.markers.addChild(g); + for (const n of data.nests) { + const { x, y } = hexCenterXY(n.col, n.row); + const txt = new Text({ text: String(n.level), style: { fontSize: 34, fill: 0xffffff, fontWeight: "bold" } }); + txt.anchor.set(0.5); + txt.position.set(x, y); + s.markers.addChild(txt); + } + }, [ready, data]); + + // Auswahl + useEffect(() => { + const s = scene.current; + if (!ready || !s) return; + s.selection.clear(); + if (selected) { + const { x, y } = hexCenterXY(selected.col, selected.row); + s.selection.poly(hexPoints(x, y, HEX_SIZE_KM)).stroke({ color: 0xffffff, width: 7 }); + } + }, [ready, selected]); + + const zoom = (f: number) => { + const s = scene.current; + if (!s) return; + const p = { x: s.app.screen.width / 2, y: s.app.screen.height / 2 }; + const ns = Math.max(MIN_SCALE, Math.min(MAX_SCALE, s.world.scale.x * f)); + const wx = (p.x - s.world.x) / s.world.scale.x; + const wy = (p.y - s.world.y) / s.world.scale.y; + s.world.scale.set(ns); + s.world.position.set(p.x - wx * ns, p.y - wy * ns); + }; + return ( +
+
+
+ + +
+
+ ); +} + +/** Ziehen, Zwei-Finger-Zoom, Mausrad, Tippen. Rückgabe: Aufräumfunktion. */ +function attachGestures(canvas: HTMLCanvasElement, world: Container, onTap: (x: number, y: number) => void): () => void { + const pts = new Map(); + let downAt = 0; + let moved = 0; + let pinch: { dist: number; scale: number; mid: { x: number; y: number } } | null = null; + + const local = (e: PointerEvent | WheelEvent) => { + const r = canvas.getBoundingClientRect(); + return { x: e.clientX - r.left, y: e.clientY - r.top }; + }; + const zoomAt = (p: { x: number; y: number }, newScale: number) => { + const s = Math.max(MIN_SCALE, Math.min(MAX_SCALE, newScale)); + const wx = (p.x - world.x) / world.scale.x; + const wy = (p.y - world.y) / world.scale.y; + world.scale.set(s); + world.position.set(p.x - wx * s, p.y - wy * s); + }; + const pinchInfo = () => { + const [a, b] = [...pts.values()]; + return { dist: Math.hypot(a.x - b.x, a.y - b.y), mid: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 } }; + }; + + const down = (e: PointerEvent) => { + canvas.setPointerCapture(e.pointerId); + pts.set(e.pointerId, local(e)); + if (pts.size === 1) { + downAt = performance.now(); + moved = 0; + } + if (pts.size === 2) { + const i = pinchInfo(); + pinch = { dist: i.dist, scale: world.scale.x, mid: i.mid }; + moved = 999; + } + }; + const move = (e: PointerEvent) => { + const prev = pts.get(e.pointerId); + if (!prev) return; + const p = local(e); + pts.set(e.pointerId, p); + if (pts.size === 1) { + world.position.set(world.x + p.x - prev.x, world.y + p.y - prev.y); + moved += Math.abs(p.x - prev.x) + Math.abs(p.y - prev.y); + } else if (pts.size === 2 && pinch) { + const i = pinchInfo(); + // Mittelpunkt mitschwenken, dann um ihn zoomen + world.position.set(world.x + i.mid.x - pinch.mid.x, world.y + i.mid.y - pinch.mid.y); + pinch.mid = i.mid; + zoomAt(i.mid, pinch.scale * (i.dist / Math.max(1, pinch.dist))); + } + }; + const up = (e: PointerEvent) => { + const p = pts.get(e.pointerId); + pts.delete(e.pointerId); + if (pts.size < 2) pinch = null; + if (p && pts.size === 0 && moved < 10 && performance.now() - downAt < 600) { + onTap((p.x - world.x) / world.scale.x, (p.y - world.y) / world.scale.y); + } + }; + const wheel = (e: WheelEvent) => { + e.preventDefault(); + zoomAt(local(e), world.scale.x * Math.exp(-e.deltaY * 0.0015)); + }; + canvas.addEventListener("pointerdown", down); + canvas.addEventListener("pointermove", move); + canvas.addEventListener("pointerup", up); + canvas.addEventListener("pointercancel", up); + canvas.addEventListener("wheel", wheel, { passive: false }); + return () => { + canvas.removeEventListener("pointerdown", down); + canvas.removeEventListener("pointermove", move); + canvas.removeEventListener("pointerup", up); + canvas.removeEventListener("pointercancel", up); + canvas.removeEventListener("wheel", wheel); + }; +} diff --git a/apps/web/src/screens/MapScreen.tsx b/apps/web/src/screens/MapScreen.tsx new file mode 100644 index 0000000..d5503a7 --- /dev/null +++ b/apps/web/src/screens/MapScreen.tsx @@ -0,0 +1,71 @@ +import { useMemo, useState } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { terrainAt } from "@tidefront/world"; +import { trpc, type BaseData } from "../lib/trpc.ts"; +import { fmtDuration, useNow } from "../lib/time.ts"; +import { fmtNum, label } from "../lib/names.ts"; +import type { Target } from "../App.tsx"; +import { HexMap } from "./HexMap.tsx"; +import { Button, Loading } from "../ui.tsx"; + +const TERRAIN: Record = { sea: "Meer", coast: "Küste", land: "Land" }; + +export function MapScreen({ base, focus, onPlan }: { base: BaseData; focus: Target | null; onPlan: (t: Target) => void }) { + const map = useQuery({ ...trpc.world.map.queryOptions(), refetchInterval: 60000 }); + const [sel, setSel] = useState(focus); + const now = useNow(); + const center = useMemo(() => focus ?? { col: base.col, row: base.row }, [focus, base.col, base.row]); + if (!map.data) return ; + const at = (t: Target | null) => { + if (!t) return null; + return { + base: map.data.bases.find((b) => b.col === t.col && b.row === t.row), + nest: map.data.nests.find((n) => n.col === t.col && n.row === t.row), + wreck: map.data.wrecks.find((w) => w.col === t.col && w.row === t.row), + }; + }; + const info = at(sel); + + return ( +
+
+ +
+ {sel && info && ( +
+
+
+
Feld {sel.col}/{sel.row} · {TERRAIN[terrainAt(sel.col, sel.row) ?? "sea"]}
+ {info.base && ( +
+ {info.base.name} ({info.base.own ? "dein Stützpunkt" : info.base.owner}) + {info.base.protection &&
🛡 {label(info.base.protection)}
} +
+ )} + {info.nest && ( +
+ Piratennest Stufe {info.nest.level} + {info.nest.empty &&
verlassen, neu besetzt in {fmtDuration((info.nest.respawnAtMs ?? now) - now)}
} +
+ )} + {info.wreck &&
Wrackfeld: {fmtNum(info.wreck.stahl)} Stahl, {fmtNum(info.wreck.elektronik)} Elektronik
} + {!info.base && !info.nest && !info.wreck &&
Hier ist nichts.
} +
+ +
+ {(info.nest || (info.base && !info.base.own)) && ( + + )} +
+ )} + {!sel && ( +
+ dein Stützpunkt + andere + Nest (Stufe) + Wrack +
+ )} +
+ ); +} diff --git a/apps/web/src/screens/Market.tsx b/apps/web/src/screens/Market.tsx new file mode 100644 index 0000000..508837c --- /dev/null +++ b/apps/web/src/screens/Market.tsx @@ -0,0 +1,116 @@ +import { useEffect, useState } from "react"; +import { keepPreviousData, useQuery } from "@tanstack/react-query"; +import { trpc, trpcClient, type BaseData } from "../lib/trpc.ts"; +import { useCommand } from "../lib/command.ts"; +import { RES_ICON, errorText, fmtNum, label } from "../lib/names.ts"; +import { fmtDuration, useNow } from "../lib/time.ts"; +import { Button, Card, ErrorLine, Loading } from "../ui.tsx"; + +export function MarketScreen({ base }: { base: BaseData }) { + const m = useQuery({ ...trpc.market.get.queryOptions(), refetchInterval: 30000 }); + const now = useNow(); + const [resource, setResource] = useState("stahl"); + const [side, setSide] = useState<"buy" | "sell">("buy"); + const [qtyText, setQtyText] = useState("100"); + const [qty, setQty] = useState(100); + const [done, setDone] = useState(null); + // Menge erst nach kurzer Pause anfragen + useEffect(() => { + const t = setTimeout(() => setQty(Math.max(0, Math.floor(Number(qtyText) || 0))), 300); + return () => clearTimeout(t); + }, [qtyText]); + const quote = useQuery({ + ...trpc.market.quote.queryOptions({ side, resource, qty: Math.max(1, qty) }), + enabled: qty > 0 && base.market.unlocked, + placeholderData: keepPreviousData, + }); + const exec = useCommand( + (i: { key: string; side: "buy" | "sell"; resource: string; qty: number; expectedPrice: number }) => trpcClient.market.trade.mutate(i), + () => [trpc.market.pathFilter().queryKey, trpc.base.pathFilter().queryKey], + ); + if (!m.data) return ; + const q = quote.data && quote.data.ok ? quote.data : null; + const sel = m.data.resources.find((r) => r.id === resource)!; + const halted = sel.haltedUntilMs > now; + + return ( +
+
+

Börse

+
+
{fmtNum(m.data.credits, 2)} Kr
+
Limit {fmtNum(base.market.creditLimit)} Kr
+
+
+ {!base.market.unlocked && ( +
+ {errorText("locked")} Deine Hafenkommandantur hat Stufe {base.buildings.find((b) => b.id === "hafenkommandantur")?.level ?? 0}. +
+ )} + + +
    + {m.data.resources.map((r) => { + const dev = (r.price / r.ref - 1) * 100; + return ( +
  • + +
  • + ); + })} +
+
+ + +
+ {(["buy", "sell"] as const).map((s) => ( + + ))} +
+ + setQtyText(e.target.value.replace(/\D/g, ""))} + /> +
+ Bestand {fmtNum(base.resources[resource] ?? 0)} · Tageslimit {fmtNum(sel.dailyUsed)}/{fmtNum(sel.dailyLimit)} · Gebühr {fmtNum(m.data.fee * 100)} % +
+ {q && ( +
+
Ausführungskurs {fmtNum(q.executionPrice, 4)} (Kurs danach {fmtNum(q.priceAfter, 4)})
+
Kurswirkung {fmtNum(q.impact * 100, 2)} % · Gebühr {fmtNum(q.feeCredits, 2)} Kr
+
{side === "buy" ? "Kosten" : "Erlös"}: {fmtNum(q.totalCredits, 2)} Kr
+ {side === "buy" &&
Lieferung per Konvoi aus {base.market.port.name}
} +
+ )} + {quote.data && !quote.data.ok && } + + {halted &&

{errorText("halted")}

} + + {done &&

{done}

} +
+
+ ); +} diff --git a/apps/web/src/screens/MissionPlan.tsx b/apps/web/src/screens/MissionPlan.tsx new file mode 100644 index 0000000..f8a241b --- /dev/null +++ b/apps/web/src/screens/MissionPlan.tsx @@ -0,0 +1,160 @@ +import { useEffect, useMemo, useState } from "react"; +import { keepPreviousData, useQuery } from "@tanstack/react-query"; +import { queryClient, trpc, trpcClient, type BaseData } from "../lib/trpc.ts"; +import { useCommand } from "../lib/command.ts"; +import { RES_ICON, errorText, fmtNum, label } from "../lib/names.ts"; +import { fmtSeconds, fmtTime } from "../lib/time.ts"; +import type { Target } from "../App.tsx"; +import { HexMap } from "./HexMap.tsx"; +import { Button, Card, ErrorLine, Loading, Stepper } from "../ui.tsx"; + +const TYPES = [ + { id: "ueberfall", text: "Überfall", hint: "Kampf am Ziel, Beute bei Sieg" }, + { id: "aufklaerung", text: "Aufklärung", hint: "Lagebild ohne Kampf" }, + { id: "transport", text: "Transport", hint: "Ladung an einen Stützpunkt" }, +] as const; + +export function MissionPlan({ base, initialTarget, onClose }: { base: BaseData; initialTarget: Target | null; onClose: () => void; onPickOnMap?: () => void }) { + const meta = useQuery({ ...trpc.meta.queryOptions(), staleTime: Infinity }); + const map = useQuery(trpc.world.map.queryOptions()); + const [type, setType] = useState<"ueberfall" | "aufklaerung" | "transport">("ueberfall"); + const [target, setTarget] = useState(initialTarget); + const [units, setUnits] = useState>({}); + const [cargo, setCargo] = useState>({}); + const [sent, setSent] = useState<{ arriveAtMs: number } | null>(null); + // Frische Bestände beim Öffnen + useEffect(() => { + void queryClient.invalidateQueries(trpc.base.pathFilter()); + }, []); + const launch = useCommand( + (i: { key: string; type: string; units: Record; col: number; row: number; cargo?: Record }) => trpcClient.mission.launch.mutate(i), + () => [trpc.base.pathFilter().queryKey], + ); + + const chosen = useMemo(() => Object.fromEntries(Object.entries(units).filter(([, n]) => n > 0)), [units]); + const cargoSent = type === "transport" ? Object.fromEntries(Object.entries(cargo).filter(([, n]) => n > 0)) : undefined; + const input = target ? { type, units: chosen, col: target.col, row: target.row, cargo: cargoSent } : null; + const preview = useQuery({ + ...trpc.mission.preview.queryOptions(input ?? { type, units: {}, col: 0, row: 0 }), + enabled: !!input && Object.keys(chosen).length > 0, + placeholderData: keepPreviousData, + }); + + if (!meta.data || !map.data) return ; + const balance = meta.data.balance; + let cp = 0, troops = 0, space = 0, cargoCap = 0; + for (const [id, n] of Object.entries(chosen)) { + const d = balance.units[id]; + cp += (d.commandPoints ?? 0) * n; + if (d.branch === "land") troops += (d.size ?? 0) * n; + space += (d.troopSpace ?? 0) * n; + cargoCap += (d.cargo ?? 0) * n; + } + const tInfo = target && { + base: map.data.bases.find((b) => b.col === target.col && b.row === target.row), + nest: map.data.nests.find((n) => n.col === target.col && n.row === target.row), + }; + const p = preview.data; + + if (sent) { + return ( + +

Der Verband ist unterwegs. Ankunft {fmtTime(sent.arriveAtMs)}.

+ +
+ ); + } + + return ( +
+
+

Mission planen

+ +
+ + +
+ {TYPES.map((t) => ( + + ))} +
+

{TYPES.find((t) => t.id === type)!.hint}

+
+ + +
+ +
+

+ {!target && "Ziel auf der Karte antippen."} + {target && tInfo?.base && <>Stützpunkt {tInfo.base.name} ({tInfo.base.owner})} + {target && tInfo?.nest && <>Piratennest Stufe {tInfo.nest.level}{tInfo.nest.empty ? " (verlassen)" : ""}} + {target && !tInfo?.base && !tInfo?.nest && Feld {target.col}/{target.row}: kein Ziel} +

+
+ + +
    + {base.units.filter((u) => u.home > 0).map((u) => ( +
  • +
    {label(u.id)} ({fmtNum(u.home)} daheim)
    + setUnits({ ...units, [u.id]: v })} /> +
  • + ))} +
+ {base.units.every((u) => u.home === 0) &&

Keine Einheiten daheim.

} +
+ Kommandopunkte base.commandPoints ? "text-red-300" : ""}`}>{fmtNum(cp, 1)}/{fmtNum(base.commandPoints)} + Truppen / Platz space ? "text-red-300" : ""}`}>{fmtNum(troops)}/{fmtNum(space)} + Ladekapazität{fmtNum(cargoCap)} +
+
+ + {type === "transport" && ( + + {balance.resources.map((r) => ( +
+ {RES_ICON[r]} {label(r)} ({fmtNum(base.resources[r] ?? 0)}) + setCargo({ ...cargo, [r]: v })} /> +
+ ))} +
+ )} + + + {!target || Object.keys(chosen).length === 0 ? ( +

Ziel und Einheiten wählen.

+ ) : !p ? ( +

Berechne …

+ ) : ( +
+ {"distanceKm" in p &&
Entfernung {fmtNum(p.distanceKm)} km
} + {p.ok ? ( + <> +
Reisezeit {fmtSeconds(p.travelSeconds)} je Richtung
+
Treibstoff {fmtNum(p.fuelCost)} (hin und zurück)
+
Ankunft {fmtTime(p.arriveAtMs)} · zurück {fmtTime(p.returnAtMs)}
+ + ) : ( +
{errorText(p.code)}
+ )} +
+ )} + + +
+
+ ); +} diff --git a/apps/web/src/screens/Reports.tsx b/apps/web/src/screens/Reports.tsx new file mode 100644 index 0000000..d06d2eb --- /dev/null +++ b/apps/web/src/screens/Reports.tsx @@ -0,0 +1,175 @@ +import { useState } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { trpc } from "../lib/trpc.ts"; +import { fmtNum, label } from "../lib/names.ts"; +import { fmtTime } from "../lib/time.ts"; +import { Button, Card, CountsLine, Loading } from "../ui.tsx"; + +type Counts = Record; +interface Phase { + phase: string; + skipped: boolean; + skipReason: string | null; + rounds: number; + before: { attacker: Counts; defender: Counts }; + after: { attacker: Counts; defender: Counts }; + entscheidend: string | null; + entscheidendSide: "attacker" | "defender" | null; +} +interface Outcome { before: Counts; survivors: Counts; losses: Counts; returned: Counts; final: Counts } +interface Battle { + winner: "attacker" | "defender"; + airSuperiority: "attacker" | "defender" | null; + landed: boolean; + phases: Phase[]; + attacker: Outcome; + defender: Outcome; + loot: Counts; + wreck: Counts; +} + +const SKIP: Record = { + no_fighters: "keine Jäger", no_opponent: "kein Gegner", no_bombers: "keine Bomber", no_targets: "keine Ziele", + no_ships: "keine Schiffe", no_landing_ships: "keine Landungsschiffe", no_troops: "keine Truppen", +}; + +export function ReportsScreen() { + const [open, setOpen] = useState(null); + const list = useQuery(trpc.report.list.queryOptions()); + if (open !== null) return setOpen(null)} />; + if (!list.data) return ; + return ( +
+

Berichte

+ {list.data.length === 0 &&

Noch keine Berichte.

} +
    + {list.data.map((r) => ( +
  • + +
  • + ))} +
+
+ ); +} + +function Diff({ before, after }: { before: Counts; after: Counts }) { + const ids = Object.keys(before).filter((id) => (before[id] ?? 0) > 0); + if (ids.length === 0) return –; + return ( +
    + {ids.map((id) => { + const lost = before[id] - (after[id] ?? 0); + return ( +
  • + {label(id)}: {fmtNum(before[id])} → {fmtNum(after[id] ?? 0)} + {lost > 0 && (−{fmtNum(lost)})} +
  • + ); + })} +
+ ); +} + +function ReportDetail({ id, onBack }: { id: number; onBack: () => void }) { + const q = useQuery(trpc.report.get.queryOptions({ id })); + if (!q.data) return q.isLoading ? :

Bericht nicht gefunden.

; + const r = q.data; + const d = r.data as Record; + return ( +
+
+

{r.title}

+ +
+

{fmtTime(r.atMs)}{r.seed !== null ? ` · Seed ${r.seed} · Balance ${r.balanceVersion}` : ""}

+ {d.battle ? : null} + {d.scout ? } owner={String(d.owner ?? "")} /> : null} + {d.nest ? : null} + {r.kind === "transport" && ( + +

Von {String(d.from)} an {String(d.to)}

+

+
+ )} + {r.kind === "leer" &&

Das Nest war bei Ankunft verlassen. Der Verband kehrt um.

} +
+ ); +} + +function BattleView({ b, names, role }: { b: Battle; names: [string, string]; role: "attacker" | "defender" }) { + const won = (b.winner === "attacker") === (role === "attacker"); + return ( + <> +
+ {won ? "Sieg" : "Niederlage"} – Angreifer {names[0]}, Verteidiger {names[1]} +
+ Luftüberlegenheit: {b.airSuperiority === null ? "keine" : b.airSuperiority === "attacker" ? names[0] : names[1]} · Landung: {b.landed ? "ja" : "nein"} +
+
+ {b.phases.map((p) => ( + {p.skipped ? `entfallen (${SKIP[p.skipReason ?? ""] ?? p.skipReason})` : `${p.rounds} Runden`}}> + {!p.skipped && ( + <> +
+
{names[0]}
+
{names[1]}
+
+ {p.entscheidend && ( +

+ Entscheidend: {label(p.entscheidend)} ({p.entscheidendSide === "attacker" ? names[0] : names[1]}) +

+ )} + + )} +
+ ))} + +
+
Beute:
+
Wrackfeld:
+
Verluste {names[0]}:
+
Rückkehrer {names[0]}:
+
Verluste {names[1]}:
+
Lazarett/Reparatur {names[1]}:
+
+
+ + ); +} + +function ScoutView({ s, owner }: { s: Record; owner: string }) { + return ( + +
+
Bestände:
+
Bunkerschutz: {fmtNum(Number(s.protectedPerResource ?? 0))} je Ressource
+
Einheiten:
+
Anlagen:
+
Gebäude: {Object.entries(s.buildings as Counts).filter(([, l]) => l > 0).map(([id, l]) => `${label(id)} ${l}`).join(", ") || "–"}
+
+
+ ); +} + +function NestScout({ n }: { n: { level: number; empty: boolean; garrison: { units: Counts; defenses: Counts; loot: Counts } | null } }) { + return ( + + {n.empty || !n.garrison ? ( +

Das Nest ist verlassen.

+ ) : ( +
+
Besatzung:
+
Anlagen:
+
Beute:
+
+ )} +
+ ); +} diff --git a/apps/web/src/screens/Troops.tsx b/apps/web/src/screens/Troops.tsx new file mode 100644 index 0000000..4d83735 --- /dev/null +++ b/apps/web/src/screens/Troops.tsx @@ -0,0 +1,143 @@ +import { useState } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { trpc, trpcClient, type BaseData, type Balance } from "../lib/trpc.ts"; +import { useCommand } from "../lib/command.ts"; +import { fmtNum, label } from "../lib/names.ts"; +import { fmtDuration, fmtSeconds, useNow } from "../lib/time.ts"; +import type { Target } from "../App.tsx"; +import { Button, Card, Cost, CountsLine, ErrorLine, Loading, Stepper } from "../ui.tsx"; +import { Progress } from "./Base.tsx"; + +const invalidateBase = () => [trpc.base.pathFilter().queryKey]; +const GROUPS: { builtIn: string; title: string }[] = [ + { builtIn: "werft", title: "Werft" }, + { builtIn: "kaserne", title: "Kaserne" }, + { builtIn: "flugfeld", title: "Flugfeld" }, + { builtIn: "anlagen", title: "Verteidigungsanlagen" }, +]; + +function scale(cost: Record | undefined, n: number): Record { + const out: Record = {}; + for (const [r, v] of Object.entries(cost ?? {})) out[r] = v * n; + return out; +} + +export function TroopsScreen({ base, onPlan, onShowOnMap }: { base: BaseData; onPlan: () => void; onShowOnMap: (t: Target) => void }) { + const meta = useQuery({ ...trpc.meta.queryOptions(), staleTime: Infinity }); + const now = useNow(); + const cancel = useCommand((i: { key: string; builtIn: string }) => trpcClient.base.cancelTraining.mutate(i), invalidateBase); + if (!meta.data) return ; + const balance = meta.data.balance; + + return ( +
+
+

Truppen

+ +
+ + + {base.missions.length === 0 &&

Keine laufenden Missionen.

} +
    + {base.missions.map((m) => ( +
  • +
    + {label(m.type)} + +
    +
    +
    + {m.status === "outbound" ? `Ankunft in ${fmtDuration(m.arriveAtMs - now)}` : `Rückkehr in ${fmtDuration(m.returnAtMs - now)}`} +
    + {m.cargoHome && Object.values(m.cargoHome).some((v) => v > 0) && ( +
    Ladung:
    + )} +
  • + ))} +
+
+ + + {GROUPS.map((g) => { + const order = base.trainingQueue.find((o) => o.builtIn === g.builtIn); + const level = g.builtIn === "anlagen" ? 1 : base.buildings.find((b) => b.id === g.builtIn)?.level ?? 0; + return ( + Stufe {level} : undefined}> + {g.builtIn === "flugfeld" &&

Stellplätze {base.aircraftSlots.used}/{base.aircraftSlots.total}

} + {order && ( +
+
+ {fmtNum(order.count)} × {label(order.id)} +
{order.finishesAt <= now ? "wird abgeschlossen …" : `noch ${fmtDuration(order.finishesAt - now)}`}
+ +
+ +
+ )} + {level < 1 ? ( + <> +

Erst {label(g.builtIn)} bauen.

+ {base.units.some((u) => u.builtIn === g.builtIn && u.home + u.away > 0) && ( +

+ Vorhanden: u.builtIn === g.builtIn).map((u) => [u.id, u.home + u.away]))} /> +

+ )} + + ) : ( +
    + {g.builtIn === "anlagen" + ? base.defenses.map((d) => ( + + )) + : base.units.filter((u) => u.builtIn === g.builtIn).map((u) => ( + + ))} +
+ )} +
+ ); + })} +
+ ); +} + +function stats(balance: Balance, id: string): string { + const u = balance.units[id] ?? balance.npcUnits[id]; + const d = balance.defenses[id]; + const a = u?.attack ?? d?.attack; + const hp = u?.hp ?? d?.hp; + const parts = [`HP ${hp}`]; + if (a) parts.push(`See ${a.see} · Luft ${a.luft} · Land ${a.land}${a.anlage ? ` · Anlage ${a.anlage}` : ""}`); + if (d?.oneShotDamageToLanding) parts.push(`${d.oneShotDamageToLanding} Schaden bei Landung`); + if (u?.cargo) parts.push(`Ladung ${u.cargo}`); + if (u?.troopSpace) parts.push(`Truppenraum ${u.troopSpace}`); + if (u?.rangeKm) parts.push(`Reichweite ${u.rangeKm} km`); + return parts.join(" · "); +} + +function TrainRow(props: { id: string; have: number; away: number; base: BaseData; balance: Balance; busy: boolean; secondsEach: number | null; cost: Record | undefined }) { + const [n, setN] = useState(1); + const cmd = useCommand((i: { key: string; id: string; count: number }) => trpcClient.base.train.mutate(i), invalidateBase); + return ( +
  • +
    +
    {label(props.id)}
    +
    {fmtNum(props.have)}{props.away > 0 ? ` (+${fmtNum(props.away)} unterwegs)` : ""}
    +
    +
    {stats(props.balance, props.id)}
    +
    + + +
    +
    + + {props.secondsEach !== null && ⏱ {fmtSeconds(props.secondsEach * n)}} +
    + +
  • + ); +} diff --git a/apps/web/src/styles.css b/apps/web/src/styles.css new file mode 100644 index 0000000..d0b324f --- /dev/null +++ b/apps/web/src/styles.css @@ -0,0 +1,24 @@ +@import "tailwindcss"; + +@theme { + --color-navy-950: #060e18; + --color-navy-900: #0b1726; + --color-navy-800: #12243a; + --color-navy-700: #1b3352; + --color-navy-600: #26476f; + --color-sea-400: #3fa7d6; + --color-sea-300: #7cc6e8; + --color-brass-400: #f2c14e; +} + +html, body, #root { height: 100%; } +body { + margin: 0; + background: var(--color-navy-950); + color: #e6eef7; + font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + -webkit-tap-highlight-color: transparent; + overscroll-behavior: none; +} +input, select, button { font: inherit; } +.tap { min-height: 44px; min-width: 44px; } diff --git a/apps/web/src/ui.tsx b/apps/web/src/ui.tsx new file mode 100644 index 0000000..daa5a20 --- /dev/null +++ b/apps/web/src/ui.tsx @@ -0,0 +1,86 @@ +import type { ReactNode } from "react"; +import { RES_ICON, fmtNum, label } from "./lib/names.ts"; + +export function Card({ title, children, right }: { title?: ReactNode; children: ReactNode; right?: ReactNode }) { + return ( +
    + {title !== undefined && ( +
    +

    {title}

    + {right} +
    + )} + {children} +
    + ); +} + +type BtnKind = "primary" | "secondary" | "danger" | "ghost"; +const KIND: Record = { + primary: "bg-sea-400 text-navy-950 font-semibold active:bg-sea-300", + secondary: "bg-navy-700 text-white active:bg-navy-600", + danger: "bg-red-700 text-white active:bg-red-600", + ghost: "bg-transparent text-sea-300 underline", +}; + +export function Button(props: { children: ReactNode; onClick?: () => void; disabled?: boolean; kind?: BtnKind; className?: string; type?: "button" | "submit" }) { + return ( + + ); +} + +export function ErrorLine({ text }: { text: string | null | undefined }) { + if (!text) return null; + return

    {text}

    ; +} + +export function Cost({ cost, have }: { cost: Record | null | undefined; have?: Record }) { + if (!cost) return null; + const parts = Object.entries(cost).filter(([, v]) => v > 0); + if (parts.length === 0) return kostenlos; + return ( + + {parts.map(([r, v]) => ( + + {RES_ICON[r] ?? ""} {fmtNum(v)} + + ))} + + ); +} + +export function Stepper({ value, onChange, max }: { value: number; onChange: (v: number) => void; max?: number }) { + const clamp = (v: number) => Math.max(0, Math.min(max ?? Infinity, Math.floor(v || 0))); + return ( +
    + + onChange(clamp(Number(e.target.value.replace(/\D/g, ""))))} + /> + + {max !== undefined && ( + + )} +
    + ); +} + +export function CountsLine({ counts }: { counts: Record | null | undefined }) { + const parts = Object.entries(counts ?? {}).filter(([, n]) => n > 0); + if (parts.length === 0) return –; + return {parts.map(([id, n]) => `${fmtNum(n)} ${label(id)}`).join(", ")}; +} + +export function Loading() { + return

    Lädt …

    ; +} diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts new file mode 100644 index 0000000..11f02fe --- /dev/null +++ b/apps/web/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts new file mode 100644 index 0000000..ba680ef --- /dev/null +++ b/apps/web/vite.config.ts @@ -0,0 +1,16 @@ +import { defineConfig } from "vite"; +import react from "@vitejs/plugin-react"; +import tailwindcss from "@tailwindcss/vite"; + +const target = process.env.TF_API ?? "http://localhost:18080"; + +export default defineConfig({ + plugins: [react(), tailwindcss()], + build: { outDir: "dist", emptyOutDir: true, chunkSizeWarningLimit: 1200 }, + server: { + proxy: { + "/trpc": { target, changeOrigin: true }, + "/ws": { target, ws: true, changeOrigin: true }, + }, + }, +}); diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..7ced5ac --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,112 @@ +# TIDEFRONT: docker compose up -d (arm64 und amd64) +# Nach außen geht nur der HTTP-Port des api-Dienstes (Vorgabe 8080, in .env: TIDEFRONT_PORT). +# TLS übernimmt der vorhandene Proxy; WebSocket läuft über denselben Port (/ws). +name: tidefront + +x-app: &app + image: tidefront:local + build: . + restart: unless-stopped + environment: + DATABASE_URL: postgres://tidefront:${POSTGRES_PASSWORD:?POSTGRES_PASSWORD in .env setzen}@postgres:5432/tidefront + VALKEY_URL: redis://valkey:6379 + INVITE_CODES: ${INVITE_CODES:-} + LOG_LEVEL: ${LOG_LEVEL:-info} + TZ: ${TZ:-Europe/Berlin} + +services: + postgres: + image: postgres:17-alpine + restart: unless-stopped + environment: + POSTGRES_USER: tidefront + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD in .env setzen} + POSTGRES_DB: tidefront + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U tidefront -d tidefront"] + interval: 10s + timeout: 5s + retries: 10 + start_period: 20s + + valkey: + image: valkey/valkey:8-alpine + restart: unless-stopped + command: ["valkey-server", "--save", "", "--appendonly", "no"] + healthcheck: + test: ["CMD", "valkey-cli", "ping"] + interval: 10s + timeout: 3s + retries: 10 + + migrate: + <<: *app + restart: "no" + command: ["node", "--enable-source-maps", "server/migrate.mjs"] + depends_on: + postgres: + condition: service_healthy + healthcheck: + test: ["CMD", "node", "-e", "process.exit(0)"] + interval: 30s + + api: + <<: *app + command: ["node", "--enable-source-maps", "server/api.mjs"] + ports: + - "${TIDEFRONT_PORT:-8080}:8080" + depends_on: + migrate: + condition: service_completed_successfully + valkey: + condition: service_healthy + healthcheck: + test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8080/healthz"] + interval: 15s + timeout: 5s + retries: 5 + start_period: 15s + + worker: + <<: *app + command: ["node", "--enable-source-maps", "server/worker.mjs"] + depends_on: + migrate: + condition: service_completed_successfully + valkey: + condition: service_healthy + healthcheck: + test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8081/"] + interval: 30s + timeout: 5s + retries: 3 + start_period: 15s + + backup: + image: postgres:17-alpine + restart: unless-stopped + entrypoint: ["sh", "/scripts/backup.sh", "loop"] + environment: + PGHOST: postgres + PGUSER: tidefront + PGPASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD in .env setzen} + PGDATABASE: tidefront + BACKUP_HOUR: ${BACKUP_HOUR:-4} + BACKUP_KEEP_DAYS: ${BACKUP_KEEP_DAYS:-14} + TZ: ${TZ:-Europe/Berlin} + volumes: + - ${BACKUP_DIR:-./backups}:/backups + - ./scripts/backup.sh:/scripts/backup.sh:ro + depends_on: + postgres: + condition: service_healthy + healthcheck: + test: ["CMD", "sh", "/scripts/backup.sh", "health"] + interval: 5m + timeout: 10s + start_period: 2m + +volumes: + pgdata: diff --git a/docs/BAUAUFTRAG.md b/docs/BAUAUFTRAG.md index 8ab6a9a..09adf2b 100644 --- a/docs/BAUAUFTRAG.md +++ b/docs/BAUAUFTRAG.md @@ -7,26 +7,43 @@ Hobbyprojekt für den Freundeskreis. Gebaut wird mit KI-Agenten. Regeln: `docs/R | Paket | Inhalt | Stand | | --- | --- | --- | | 0 Fundament | Gerüst, Regel-Spezifikation, Balance-Daten | fertig | -| 1 Spielregeln | `packages/game-core`: Ressourcen, Bau, Einheiten, Missionen, Kampf, Freibeuter-Kartell, Schutz | fertig, 104 Tests; offene Punkte unten | -| 4 Börsenkern | `packages/game-core/src/market`: Sofortkauf und -verkauf, Schutzregeln, Journal | fertig, 28 Tests | -| 2 Server | Datenbank, Ereignis-Queue, Befehle, Konten, WebSocket | offen | -| 3 Oberfläche | PWA nach den Mockups | offen | -| 5 Betrieb | Dockerfile, Compose, Sicherung, Startanleitung | offen | +| 1 Spielregeln | `packages/game-core`: Ressourcen, Bau, Einheiten, Missionen, Kampf, Freibeuter-Kartell, Schutz | fertig, offene Punkte aus Stand 1 behoben (Stand 2) | +| 4 Börsenkern | `packages/game-core/src/market`: Sofortkauf und -verkauf, Schutzregeln, Journal | fertig | +| 2 Server | Datenbank, Ereignis-Queue, Befehle, Konten, WebSocket | fertig (Stand 2), Integrationstests gegen PostgreSQL | +| 3 Oberfläche | PWA mit Basis, Karte, Truppen, Mission planen, Kampfbericht, Börse | fertig (Stand 2) | +| 5 Betrieb | Dockerfile, Compose, Sicherung, Startanleitung | fertig (Stand 2), läuft auf `speech.local:8080` | | 6 Prüfung | Unabhängiger Testlauf und Durchspielen im Handy-Format | offen | -## Offene Punkte am Regelkern +## Offene Punkte am Regelkern (Stand 2: erledigt) Auslegungen stehen in `packages/game-core/ENTSCHEIDUNGEN.md` und `packages/game-core/src/market/ENTSCHEIDUNGEN.md`. -- **Restschaden verfällt (Regelfehler):** Weil Schaden unterhalb der Lebenspunkte einer Einheit je Runde verfällt, sind kleine Verbände - und die Überfälle des Kartells fast wirkungslos. Korrektur: Restschaden je Einheitentyp über Runden und Phasen mitführen; - REGELN.md und `combat.ts` anpassen, Test ergänzen. -- Kampfbericht auf den Stützpunkt anwenden (Bestände, Beute, Rückkehr der Einheiten) fehlt; gehört zu Paket 2 oder als Funktion in den Kern. -- Ablauf von Aufklärung und Transport am Ziel fehlt. -- Ohne Regel und nicht umgesetzt: Schwachziel-Regel (`loot.weakTarget*`), Wrack-Verfall, Radar-Vorwarnzeit, Abbruch von Bau und Ausbildung. -- Der Angriffswert `anlage` der Bodentruppen und `kuestenbatterie.attack.land` werden nicht genutzt; Auslegung A1 bis A4 prüfen. -- Balance ist nicht simuliert. Ein Simulations-Runner mit Bots steht aus. -- Typprüfung der Tests fehlt (`@types/node`); nach `npm install` nachholen. +- [x] **Restschaden** wird je Einheitentyp über Runden und Phasen mitgeführt (REGELN.md, `combat.ts`, Tests). +- [x] Kampfbericht auf Stützpunkte anwenden: `applyDefenseResult`, `returnMission`, `attackerReturning` (`resolution.ts`). +- [x] Ablauf von Aufklärung und Transport am Ziel: `scoutBase`, `deliverCargo`; Regeln in REGELN.md. +- [x] Schwachziel-Regel, Wrack-Verfall und Bergung, Radar-Vorwarnzeit, Abbruch von Bau und Ausbildung: geregelt und umgesetzt. +- [x] `anlage` der Bodentruppen wirkt gegen die Bunkerlinie, `kuestenbatterie.attack.land` feuert im Bodenkampf mit (A1, A3). +- [x] Simulations-Runner: `npm run sim` (Kampf-Matrix und Bau-Bot). Ergebnisse und Balance-Hinweise in ENTSCHEIDUNGEN.md, Abschnitt C; + `balance.json` ist unverändert. +- [x] Typprüfung: `npm run typecheck` (TypeScript mit `@types/node`) über alle Pakete und Tests. + +## Festlegungen des Servers (Stand 2) + +- Stützpunkt-Zustand liegt als `BaseState` (JSON) in `base.state`; jede Änderung sperrt die Zeile (`FOR UPDATE`). + Sperrreihenfolge: Ereignis, Mission, Stützpunkte aufsteigend, Spieler, Marktzeile. +- Ereignisse: `build_complete`, `training_complete`, `mission_arrive`, `mission_return`, `raid_launch`, `raid_arrive`, + `delivery_arrive`. Handler rechnen mit dem Fälligkeitszeitpunkt, nicht mit der Uhr des Workers. Fehlgeschlagene + Ereignisse werden mit wachsendem Abstand bis zu fünfmal wiederholt, danach `failed`. +- Befehle und Lesezugriffe verarbeiten zuerst die fälligen Ereignisse des eigenen Stützpunkts (je eine eigene Transaktion), + dann läuft der Befehl in einer Transaktion. Abgelehnte Befehle werden mit ihrem Code im Befehlsprotokoll gespeichert. +- Schutz des Ziels wird beim Planen eines Überfalls geprüft, nicht erneut bei Ankunft. +- Kartell: läuft alle `raidIntervalHours` je Stützpunkt aus und kommt 60 Minuten später an; Schutz wird bei Auslaufen und + Ankunft geprüft. Der Verband wird beim Auslaufen nach der dann vorhandenen Verteidigung zusammengestellt. +- Aufklärung wird in Meilenstein 1 nicht abgefangen. Transport geht nur an fremde Spielerstützpunkte (ein Stützpunkt je Spieler). +- Börse: Startkredite 0; Bestände werden für die Börse abgerundet, der Stützpunkt behält Nachkommastellen. Lieferungen + buchen bei Ankunft `delivery:` an `player:`. Der Worker prüft alle 10 Minuten das Journal gegen Kredite und offene + Lieferungen (`audit_run`). +- Einladungscodes kommen aus `INVITE_CODES` und werden bei jedem `migrate` ergänzt. ## Festlegungen für den Betrieb diff --git a/packages/engine/test/engine.test.ts b/packages/engine/test/engine.test.ts index f9d395a..a3477bb 100644 --- a/packages/engine/test/engine.test.ts +++ b/packages/engine/test/engine.test.ts @@ -229,3 +229,24 @@ test("Aufräumen und Prüflauf laufen ohne Fehler", async () => { await cleanup(engine, Date.now(), 48); assert.equal((await auditLedger(engine)).ok, true); }); + +test("Transport liefert Ladung beim Ziel ab; Wrackgut wird geborgen", async () => { + const a = await newPlayer("Jana", 24); + const b = await newPlayer("Kurt", 27); + await patchBase(a.baseId, (s) => { s.units = { landungsschiff: 1 }; s.resources.treibstoff = 50000; s.resources.stahl = 3000; }); + const before = (await stateOf(b.baseId)).resources.stahl; + const m = await launchMission(engine, a.playerId, key(), { type: "transport", units: { landungsschiff: 1 }, col: b.col, row: b.row, cargo: { stahl: 1000 } }); + assert.equal(m.ok, true, JSON.stringify(m)); + const [row] = await db.select().from(tables.mission).where(eq(tables.mission.id, (m as { missionId: number }).missionId)); + // Wrack am Ziel, eine Stunde vor Ankunft entstanden (2 % verfallen) + await db.insert(tables.wreck).values({ col: b.col, row: b.row, stahl: 500, elektronik: 100, createdAt: new Date(row.arriveAt.getTime() - HOUR) }); + await processDue(engine, row.arriveAt.getTime() + 1); + assert.ok((await stateOf(b.baseId)).resources.stahl >= before + 1000); + const [back] = await db.select().from(tables.mission).where(eq(tables.mission.id, row.id)); + const cargo = back.cargoHome as Record; + assert.ok(cargo.stahl > 400 && cargo.elektronik > 80, JSON.stringify(cargo)); + const left = await db.select().from(tables.wreck).where(sql`${tables.wreck.col} = ${b.col} and ${tables.wreck.row} = ${b.row}`); + assert.equal(left.length, 0); + await processDue(engine, back.returnAt!.getTime() + 1); + assert.equal((await stateOf(a.baseId)).units.landungsschiff, 1); +}); diff --git a/scripts/backup.sh b/scripts/backup.sh new file mode 100755 index 0000000..8bf7786 --- /dev/null +++ b/scripts/backup.sh @@ -0,0 +1,53 @@ +#!/bin/sh +# Sicherung der Datenbank (läuft im backup-Container, postgres-Image). +# loop tägliche Sicherung um BACKUP_HOUR Uhr, beim Start sofort, falls die letzte älter als 24 h ist +# once eine Sicherung jetzt +# health 0, wenn die letzte erfolgreiche Sicherung höchstens 26 Stunden alt ist +# restore DATEI stellt DATEI in die laufende Datenbank wieder her (api und worker vorher stoppen!) +# restore-test DATEI stellt DATEI in die Probe-Datenbank tidefront_restore_test her und zählt Zeilen +set -eu +DIR=/backups +KEEP=${BACKUP_KEEP_DAYS:-14} +HOUR=${BACKUP_HOUR:-4} + +backup_once() { + ts=$(date +%Y%m%d-%H%M%S) + tmp="$DIR/.tidefront-$ts.dump.part" + pg_dump -Fc -f "$tmp" + mv "$tmp" "$DIR/tidefront-$ts.dump" + date +%s > "$DIR/.last-ok" + find "$DIR" -maxdepth 1 -name 'tidefront-*.dump' -mtime +"$KEEP" -delete + echo "backup ok: tidefront-$ts.dump" +} + +last_age() { + if [ -f "$DIR/.last-ok" ]; then echo $(( $(date +%s) - $(cat "$DIR/.last-ok") )); else echo 999999999; fi +} + +case "${1:-loop}" in + once) backup_once ;; + health) [ "$(last_age)" -le $((26 * 3600)) ] ;; + restore) + f=${2:?Datei angeben} + pg_restore --clean --if-exists --no-owner -d "$PGDATABASE" "$f" + echo "restore ok: $f" ;; + restore-test) + f=${2:?Datei angeben} + psql -d postgres -qc 'drop database if exists tidefront_restore_test' + psql -d postgres -qc 'create database tidefront_restore_test' + pg_restore --no-owner -d tidefront_restore_test "$f" + psql -d tidefront_restore_test -Atc "select 'player=' || count(*) from player union all select 'base=' || count(*) from base union all select 'game_event=' || count(*) from game_event union all select 'trade_ledger=' || count(*) from trade_ledger" + psql -d postgres -qc 'drop database tidefront_restore_test' + echo "restore-test ok: $f" ;; + loop) + mkdir -p "$DIR" + if [ "$(last_age)" -gt $((24 * 3600)) ]; then backup_once || echo "backup failed"; fi + while true; do + now=$(date +%s) + target=$(date -d "$(date +%Y-%m-%d) $HOUR:00:00" +%s 2>/dev/null || echo $((now + 86400))) + [ "$target" -le "$now" ] && target=$((target + 86400)) + sleep $((target - now)) + backup_once || echo "backup failed" + done ;; + *) echo "unbekannt: $1" >&2; exit 2 ;; +esac