mirror of
https://github.com/db9979/tidefront.git
synced 2026-12-06 12:54:09 +01:00
- Geleitabteilung aus der Besatzung begleitet Ertragskonvois und kämpft bei Abfangversuchen (Kartell, Kriegsgegner); verteidigt das Feld nicht, Rest bleibt gültige Besatzung - Verstärkung: Besetzen gegen eigenes Feld fügt Schiffe der Besatzung hinzu (auch aus anderem Hafen, Veteranen gewichtet gemischt) - Radar-Vorwarnung (field_warning) bei Spielerangriffen auf Felder, Push und Meldung - Wochenziele feldertrag und gruendung - Balance fields: radarWarningFactor 0.5, escortMinRemainCommandPoints 6 - Migration 0016_felder2 (resource_field.escort), Simulation, Doku, Tests
116 lines
5.9 KiB
TypeScript
116 lines
5.9 KiB
TypeScript
// Wochenziele, Datenbankseite: Vergabe (lazy, deterministisch, idempotent) und Fortschritt. Der Fortschritt
|
|
// kommt über recordAchievement (achievements.ts): derselbe Zähler schreibt Erfolge und Wochenziele fort.
|
|
import { and, asc, count, countDistinct, eq, gte, isNotNull, isNull, lt, ne, sql } from "drizzle-orm";
|
|
import { protectionStatus, settle } from "@tidefront/game-core";
|
|
import { tables, type DbOrTx } from "@tidefront/db";
|
|
import { balance } from "./context.ts";
|
|
import { baseOfPlayer } from "./store.ts";
|
|
import { modsOf } from "./modifiers.ts";
|
|
import { addDays, poolContext } from "./challenge-pool.ts";
|
|
import { drawWeek, weekKey, weeklyReward, weekStartMs, WEEKLY_DERIVED, type WeeklyContext } from "./achievement-defs.ts";
|
|
|
|
export type WeeklyRow = typeof tables.weeklyGoal.$inferSelect;
|
|
const wg = tables.weeklyGoal;
|
|
|
|
/** Kontext für die Auswahl aus dem Stützpunkt des Spielers; null ohne Hafen. */
|
|
export async function weeklyContextFor(tx: DbOrTx, playerId: number, atMs: number): Promise<WeeklyContext | null> {
|
|
const b = await baseOfPlayer(tx, playerId); // Mehrere Häfen: bewusst Heimathafen (Auswahl nach Heimathafen)
|
|
if (!b) return null;
|
|
const mods = await modsOf(tx, b, atMs);
|
|
const state = settle(b.state, atMs, balance, mods);
|
|
const [o] = await tx.select({ n: countDistinct(tables.base.playerId) }).from(tables.base).where(ne(tables.base.playerId, playerId));
|
|
const raidsPossible = protectionStatus(state.protection, atMs, balance).reason !== "anfaengerschutz";
|
|
const [m] = await tx.select({ allianceId: tables.allianceMember.allianceId }).from(tables.allianceMember).where(eq(tables.allianceMember.playerId, playerId));
|
|
let allied = false;
|
|
if (m) {
|
|
const [n] = await tx.select({ n: count() }).from(tables.allianceMember).where(eq(tables.allianceMember.allianceId, m.allianceId));
|
|
allied = (n?.n ?? 0) >= 2;
|
|
}
|
|
const [nb] = await tx.select({ n: count() }).from(tables.base).where(eq(tables.base.playerId, playerId));
|
|
return { ...poolContext(state, { others: (o?.n ?? 0) > 0, raidsPossible }, mods), allied, bases: nb?.n ?? 1 };
|
|
}
|
|
|
|
export async function weekRows(tx: DbOrTx, playerId: number, week: string): Promise<WeeklyRow[]> {
|
|
return tx.select().from(wg).where(and(eq(wg.playerId, playerId), eq(wg.week, week))).orderBy(asc(wg.slot));
|
|
}
|
|
|
|
/** Vergibt die drei Ziele der Woche, falls noch nicht geschehen. Gleichzeitige Aufrufe sind harmlos. */
|
|
export async function ensureWeekly(tx: DbOrTx, playerId: number, week: string, atMs: number): Promise<WeeklyRow[]> {
|
|
const existing = await weekRows(tx, playerId, week);
|
|
if (existing.length >= 3) return existing;
|
|
const c = await weeklyContextFor(tx, playerId, atMs);
|
|
if (!c) return existing;
|
|
const reward = weeklyReward(c.stage);
|
|
await tx
|
|
.insert(wg)
|
|
.values(drawWeek(c, `${playerId}|${week}`).map((d) => ({ playerId, week, slot: d.slot, kind: d.kind, param: d.param, target: d.target, reward })))
|
|
.onConflictDoNothing();
|
|
return weekRows(tx, playerId, week);
|
|
}
|
|
|
|
/**
|
|
* Fortschritt auf die offenen Wochenziele der Art `kind` in der Woche von atMs (vergibt die laufende Woche bei
|
|
* Bedarf). level: nur Ziele, deren Zusatz als Zahl höchstens so groß ist (Nest-Stufe).
|
|
*/
|
|
export async function advanceWeekly(tx: DbOrTx, playerId: number, kind: string, amount: number, atMs: number, level?: number): Promise<number> {
|
|
const week = weekKey(atMs);
|
|
if (week === weekKey(Date.now())) await ensureWeekly(tx, playerId, week, atMs);
|
|
const conds = [eq(wg.playerId, playerId), eq(wg.week, week), eq(wg.kind, kind), isNull(wg.completedAt)];
|
|
if (level !== undefined) conds.push(sql`(${wg.param} is null or (${wg.param})::int <= ${level})`);
|
|
const amt = Math.floor(amount);
|
|
const next = sql`least(${wg.target}, ${wg.progress} + ${amt}::int)`;
|
|
const at = new Date(atMs).toISOString();
|
|
const done = await tx
|
|
.update(wg)
|
|
.set({ progress: next, completedAt: sql`case when ${next} >= ${wg.target} then ${at}::timestamptz else null end` })
|
|
.where(and(...conds))
|
|
.returning({ id: wg.id });
|
|
return done.length;
|
|
}
|
|
|
|
/** Ziele, deren Stand aus dem Zustand gelesen wird (abgeholte Tagesbefehle, gegründete Häfen der Woche): beim Abruf fortschreiben. */
|
|
export async function refreshWeeklyDerived(tx: DbOrTx, playerId: number, rows: WeeklyRow[], nowMs: number): Promise<WeeklyRow[]> {
|
|
const open = rows.filter((r) => !r.completedAt && WEEKLY_DERIVED.has(r.kind));
|
|
if (open.length === 0) return rows;
|
|
const out = new Map(rows.map((r) => [r.id, r]));
|
|
for (const r of open) {
|
|
const n = r.kind === "gruendung" ? await foundedInWeek(tx, playerId, r.week) : await dailiesInWeek(tx, playerId, r.week);
|
|
const progress = Math.min(r.target, Math.max(r.progress, n));
|
|
if (progress === r.progress) continue;
|
|
const completedAt = progress >= r.target ? new Date(nowMs) : null;
|
|
await tx.update(wg).set({ progress, completedAt }).where(and(eq(wg.id, r.id), isNull(wg.completedAt)));
|
|
out.set(r.id, { ...r, progress, completedAt });
|
|
}
|
|
return rows.map((r) => out.get(r.id)!);
|
|
}
|
|
|
|
/** Abgeholte Tagesbefehle in der Woche. */
|
|
async function dailiesInWeek(tx: DbOrTx, playerId: number, week: string): Promise<number> {
|
|
const dc = tables.dailyChallenge;
|
|
const [n] = await tx
|
|
.select({ n: count() })
|
|
.from(dc)
|
|
.where(and(
|
|
eq(dc.playerId, playerId),
|
|
isNotNull(dc.claimedAt),
|
|
gte(dc.claimedAt, new Date(weekStartMs(week))),
|
|
lt(dc.claimedAt, new Date(weekStartMs(addDays(week, 7)))),
|
|
));
|
|
return n?.n ?? 0;
|
|
}
|
|
|
|
/** Mehrere Häfen: in der Woche gegründete Häfen (Kolonien, nicht der Heimathafen). */
|
|
async function foundedInWeek(tx: DbOrTx, playerId: number, week: string): Promise<number> {
|
|
const b = tables.base;
|
|
const [n] = await tx
|
|
.select({ n: count() })
|
|
.from(b)
|
|
.where(and(
|
|
eq(b.playerId, playerId),
|
|
eq(b.isHome, false),
|
|
gte(b.createdAt, new Date(weekStartMs(week))),
|
|
lt(b.createdAt, new Date(weekStartMs(addDays(week, 7)))),
|
|
));
|
|
return n?.n ?? 0;
|
|
}
|