Add solo Expeditions, the second Guilde des Veilleurs quest of Sokko TCG
- Every catalog card carries expedition tags and every collection a stat profile, validated at load; twelve destinations live server-side so hidden ones stay secret. - Pure rules compute card power, per-slot requirements, roles, dangers, the long-trip malus, the score (one more star never raises it) and loot proportional to the chosen duration. - A simulator script and a balance test guard the design thresholds; agent docs and a new-card skill explain how to tag new cards. - Migration 8 adds Éclats d'étoile, expedition settings stored as one validated JSON, daily destinations, expeditions, members and slots, and rebuilds gift_packs so a pack can come from an expedition. - Players launch a solo expedition from the Guild, see an exact preview, and claim their loot when it returns; the card sheet shows cards away on an expedition. - Administration › Guilde tunes every value with server-side bounds, toggles destinations and cancels running expeditions; expeditions stay closed until an administrator opens them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
0ef213cf4f
commit
8bb1d53d70
46 changed files with 4752 additions and 213 deletions
|
|
@ -4,6 +4,7 @@ import { readFile } from "node:fs/promises";
|
|||
import { join, resolve } from "node:path";
|
||||
import { CardsDatabase } from "./database.js";
|
||||
import { loadCardsCatalog, publicCatalog } from "./catalog.js";
|
||||
import { DEFAULT_DESTINATIONS_PATH, loadExpeditionDestinations } from "./expedition-content.js";
|
||||
import { CardsService, DEV_DISCORD_ID } from "./service.js";
|
||||
import { bool, createRateLimiter, json } from "../http.js";
|
||||
|
||||
|
|
@ -104,6 +105,7 @@ export function createCardsApiHandler({
|
|||
allowProductionDevAuth = false,
|
||||
databasePath = env.CARDS_DB_PATH || join(projectRoot, ".local", "nebula-cards.sqlite"),
|
||||
catalogPath = join(projectRoot, "website", "public", "data", "cards", "catalog.json"),
|
||||
destinationsPath = DEFAULT_DESTINATIONS_PATH,
|
||||
now = Date.now,
|
||||
random,
|
||||
fetchImpl = fetch,
|
||||
|
|
@ -127,7 +129,8 @@ export function createCardsApiHandler({
|
|||
if (env.NODE_ENV === "production" && !privacyController) throw new TypeError("CARDS_PRIVACY_CONTROLLER is required when Sokko TCG is enabled in production.");
|
||||
const catalog = loadCardsCatalog(catalogPath);
|
||||
database = new CardsDatabase(databasePath);
|
||||
service = new CardsService({ database, catalog, now, random, devPerks });
|
||||
const destinations = loadExpeditionDestinations(destinationsPath, catalog);
|
||||
service = new CardsService({ database, catalog, now, random, devPerks, destinations });
|
||||
}
|
||||
const secureCookies = env.NODE_ENV === "production" || String(env.CARDS_PUBLIC_ORIGIN || "").startsWith("https://");
|
||||
const adminIds = new Set(String(env.CARDS_ADMIN_DISCORD_IDS || "").split(",").map((item) => item.trim()).filter(Boolean));
|
||||
|
|
@ -295,6 +298,34 @@ export function createCardsApiHandler({
|
|||
json(res, 200, service.guessDaily(session.player.id, { day: body.day, cardId: body.cardId }));
|
||||
return true;
|
||||
}
|
||||
if (req.method === "GET" && url.pathname === "/api/cards/expeditions") {
|
||||
json(res, 200, service.expeditions.getExpeditions(session.player.id));
|
||||
return true;
|
||||
}
|
||||
if (req.method === "POST" && url.pathname === "/api/cards/expeditions/preview") {
|
||||
rateLimit(req, "expedition-preview", 120);
|
||||
json(res, 200, service.expeditions.preview(session.player.id, await readBody(req)));
|
||||
return true;
|
||||
}
|
||||
if (req.method === "POST" && url.pathname === "/api/cards/expeditions") {
|
||||
rateLimit(req, "expedition-start", 30);
|
||||
json(res, 201, service.expeditions.startSolo(session.player.id, await readBody(req), String(req.headers["idempotency-key"] || "")));
|
||||
return true;
|
||||
}
|
||||
const expeditionClaim = routeMatch(url.pathname, /^\/api\/cards\/expeditions\/([^/]+)\/claim$/);
|
||||
if (req.method === "POST" && expeditionClaim) {
|
||||
json(res, 200, service.expeditions.claim(session.player.id, expeditionClaim[0]));
|
||||
return true;
|
||||
}
|
||||
if (req.method === "PUT" && url.pathname === "/api/cards/admin/expeditions/settings") {
|
||||
json(res, 200, service.expeditions.updateSettings(session.player.id, (await readBody(req)).settings));
|
||||
return true;
|
||||
}
|
||||
const expeditionCancel = routeMatch(url.pathname, /^\/api\/cards\/admin\/expeditions\/([^/]+)\/cancel$/);
|
||||
if (req.method === "POST" && expeditionCancel) {
|
||||
json(res, 200, service.expeditions.cancel(session.player.id, expeditionCancel[0]));
|
||||
return true;
|
||||
}
|
||||
if (req.method === "GET" && url.pathname === "/api/cards/admin/dashboard") {
|
||||
json(res, 200, service.getAdminDashboard(session.player.id));
|
||||
return true;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
// Rôle : charge et valide le catalogue public, ses finitions et effets Sokko TCG.
|
||||
import { readFileSync } from "node:fs";
|
||||
import { STAT_IDS } from "./expedition-rules.js";
|
||||
|
||||
const RARITY_IDS = new Set(["common", "rare", "epic", "legendary", "mythic"]);
|
||||
const PARTICLE_SHAPE_KINDS = new Set(["sparks", "snowflakes"]);
|
||||
|
|
@ -13,6 +14,9 @@ export const FULL_ART_FORMAT = "full-art";
|
|||
export const MATCH_HOLO_PALETTE_ID = "match-holo";
|
||||
const CARD_IMAGE_PATTERN = /^\/static\/img\/cards\/[a-z0-9-]+\/(?:common|rare|epic|legendary)\/[a-z0-9_]+\.webp$/;
|
||||
const PACK_BACK_IMAGE_PATTERN = /^\/static\/img\/cards\/[a-z0-9-]+\/back\.webp$/;
|
||||
// Étiquettes d'expédition : vocabulaire fermé, par famille (personnage, lieu, thème, objet).
|
||||
export const EXPEDITION_TAG_PATTERN = /^(personnage|lieu|theme|objet):[a-z0-9-]+$/;
|
||||
const MAX_CARD_TAGS = 8;
|
||||
|
||||
function requireUnique(items, label) {
|
||||
const ids = new Set();
|
||||
|
|
@ -24,6 +28,35 @@ function requireUnique(items, label) {
|
|||
return ids;
|
||||
}
|
||||
|
||||
// Profil d'expédition : la part de la Puissance donnée à chaque stat, en entiers dont la somme vaut 100.
|
||||
export function validExpeditionProfile(profile) {
|
||||
if (!profile || typeof profile !== "object" || Array.isArray(profile) || Object.keys(profile).length !== STAT_IDS.length) return false;
|
||||
if (STAT_IDS.some((stat) => !Number.isInteger(profile[stat]) || profile[stat] < 0 || profile[stat] > 100)) return false;
|
||||
return STAT_IDS.reduce((sum, stat) => sum + profile[stat], 0) === 100;
|
||||
}
|
||||
|
||||
function validateExpeditionTags(tags) {
|
||||
if (!Array.isArray(tags) || !tags.length) throw new TypeError("Cards catalog expeditionTags must be a non-empty array.");
|
||||
const ids = requireUnique(tags, "expeditionTags");
|
||||
for (const tag of tags) {
|
||||
if (!EXPEDITION_TAG_PATTERN.test(tag.id) || typeof tag.label !== "string" || !tag.label || tag.label.length > 40) {
|
||||
throw new TypeError(`Invalid expedition tag ${tag.id}: family:name id and a 1 to 40 character label.`);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
function validateCardExpedition(card, tagIds) {
|
||||
const expedition = card.expedition;
|
||||
if (!expedition || !Array.isArray(expedition.tags) || !expedition.tags.length || expedition.tags.length > MAX_CARD_TAGS) {
|
||||
throw new TypeError(`Card ${card.id} needs 1 to ${MAX_CARD_TAGS} expedition tags.`);
|
||||
}
|
||||
if (new Set(expedition.tags).size !== expedition.tags.length) throw new TypeError(`Card ${card.id} repeats an expedition tag.`);
|
||||
const unknown = expedition.tags.find((tag) => !tagIds.has(tag));
|
||||
if (unknown) throw new TypeError(`Card ${card.id} uses unknown expedition tag ${unknown}.`);
|
||||
if (expedition.profile != null && !validExpeditionProfile(expedition.profile)) throw new TypeError(`Card ${card.id} expedition profile must give integer shares of the four stats summing to 100.`);
|
||||
}
|
||||
|
||||
export function validateCardsCatalog(catalog) {
|
||||
if (!catalog || catalog.version !== 1) throw new TypeError("Cards catalog version must be 1.");
|
||||
for (const key of ["rarities", "effectPresets", "effectPalettes", "particleShapes", "particlePalettes", "particlePresets", "openingEffects", "finishes", "collections", "cards", "editions"]) {
|
||||
|
|
@ -40,6 +73,7 @@ export function validateCardsCatalog(catalog) {
|
|||
const collectionIds = requireUnique(catalog.collections, "collections");
|
||||
const cardIds = requireUnique(catalog.cards, "cards");
|
||||
requireUnique(catalog.editions, "editions");
|
||||
const expeditionTagIds = validateExpeditionTags(catalog.expeditionTags);
|
||||
if ([...RARITY_IDS].some((id) => !rarityIds.has(id))) throw new TypeError("Cards catalog must declare all supported rarities.");
|
||||
// Poids recommandés, proposés par l'administration pour réinitialiser les taux de tirage d'un paquet.
|
||||
validateRarityWeights(Object.fromEntries(catalog.rarities.map((rarity) => [rarity.id, rarity.recommendedWeight])), rarityIds, "recommended weights");
|
||||
|
|
@ -116,6 +150,7 @@ export function validateCardsCatalog(catalog) {
|
|||
|| !COLOR_PATTERN.test(collection.back?.secondary)) {
|
||||
throw new TypeError(`Invalid pack presentation for collection ${collection.id}.`);
|
||||
}
|
||||
if (!validExpeditionProfile(collection.expedition?.profile)) throw new TypeError(`Collection ${collection.id} needs an expedition profile giving integer shares of the four stats summing to 100.`);
|
||||
}
|
||||
|
||||
for (const card of catalog.cards) {
|
||||
|
|
@ -130,6 +165,7 @@ export function validateCardsCatalog(catalog) {
|
|||
throw new TypeError(`Card ${card.id} ${cutoutKey === "cutoutImage" ? "cutout" : "full cutout"} image must be its ${label} suffixed with __cutout.`);
|
||||
}
|
||||
}
|
||||
validateCardExpedition(card, expeditionTagIds);
|
||||
}
|
||||
|
||||
for (const edition of catalog.editions) {
|
||||
|
|
|
|||
158
services/cards/content/expedition-destinations.json
Normal file
158
services/cards/content/expedition-destinations.json
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
[
|
||||
{
|
||||
"id": "light-currents",
|
||||
"name": "Les Courants de Lumière",
|
||||
"description": "Les courants qui relient les îles changent de route chaque nuit. Il faut lire les étoiles pour ne pas s'y perdre.",
|
||||
"coverCardId": "stellar-current-otter",
|
||||
"stats": ["orientation", "bravoure", "endurance", "fortune"],
|
||||
"conditions": [{ "type": "tag", "tag": "theme:voyage" }],
|
||||
"dangers": [
|
||||
{ "id": "crosscurrent", "label": "Courant contraire", "stat": "orientation", "unlessTags": ["lieu:vide"] },
|
||||
{ "id": "drifting-isle", "label": "Île à la dérive", "stat": "bravoure", "unlessTags": ["theme:constellations"] }
|
||||
],
|
||||
"hidden": false
|
||||
},
|
||||
{
|
||||
"id": "scale-crater",
|
||||
"name": "Le Cratère de l'Écaille",
|
||||
"description": "Le cratère où la Salamandre a trouvé l'Écaille du Néant. Les météorites y tombent encore, toutes brûlantes.",
|
||||
"coverCardId": "astral-ember-salamander",
|
||||
"stats": ["bravoure", "orientation", "fortune", "endurance"],
|
||||
"conditions": [{ "type": "tag", "tag": "theme:veilleurs" }],
|
||||
"dangers": [
|
||||
{ "id": "meteor-shower", "label": "Pluie de météores", "stat": "bravoure", "unlessTags": ["theme:cometes"] },
|
||||
{ "id": "crater-smoke", "label": "Fumées du cratère", "stat": "orientation", "unlessTags": ["theme:veilleurs"] }
|
||||
],
|
||||
"hidden": false
|
||||
},
|
||||
{
|
||||
"id": "long-night-ice",
|
||||
"name": "Les Glaces de la Longue Nuit",
|
||||
"description": "Loin du Soleil, les îles se couvrent de glace. Seuls les plus endurants traversent les lacs gelés jusqu'au bout.",
|
||||
"coverCardId": "starlit-ice-penguin",
|
||||
"stats": ["endurance", "bravoure", "orientation", "fortune"],
|
||||
"conditions": [{ "type": "tag", "tag": "theme:hiver" }],
|
||||
"dangers": [
|
||||
{ "id": "blizzard", "label": "Blizzard", "stat": "orientation", "unlessTags": ["theme:hiver"] },
|
||||
{ "id": "thin-ice", "label": "Glace fragile", "stat": "endurance", "unlessTags": ["lieu:glaces"] }
|
||||
],
|
||||
"hidden": false
|
||||
},
|
||||
{
|
||||
"id": "level-isles",
|
||||
"name": "Les Îles-Niveaux",
|
||||
"description": "Les rêves de jeu du Panda forment des îles pleines de blocs, de pièces et de coffres. Chaque niveau cache un trésor.",
|
||||
"coverCardId": "island-arcade-cabinet",
|
||||
"stats": ["fortune", "bravoure", "endurance", "orientation"],
|
||||
"conditions": [{ "type": "tag", "tag": "lieu:iles-jeux" }],
|
||||
"dangers": [
|
||||
{ "id": "final-boss", "label": "Boss de fin", "stat": "bravoure", "unlessTags": ["theme:aventure"] },
|
||||
{ "id": "falling-blocks", "label": "Pluie de blocs", "stat": "fortune", "unlessTags": ["personnage:cameleon", "theme:tresor"] }
|
||||
],
|
||||
"hidden": false
|
||||
},
|
||||
{
|
||||
"id": "milky-way-band",
|
||||
"name": "La Bande de la Voie Lactée",
|
||||
"description": "Là où dort le Panda, la poussière d'étoiles s'assemble en rêves. On y trouve parfois une île qui vient de naître.",
|
||||
"coverCardId": "milky-way-panda",
|
||||
"stats": ["fortune", "orientation", "bravoure", "endurance"],
|
||||
"conditions": [{ "type": "tag", "tag": "theme:reves" }],
|
||||
"dangers": [
|
||||
{ "id": "deep-sleep", "label": "Sommeil profond", "stat": "endurance", "unlessTags": ["theme:nuit"] },
|
||||
{ "id": "dust-storm", "label": "Tempête de poussière", "stat": "orientation", "unlessTags": ["theme:poussiere"] }
|
||||
],
|
||||
"hidden": false
|
||||
},
|
||||
{
|
||||
"id": "dawn-shore",
|
||||
"name": "Le Rivage de l'Aube",
|
||||
"description": "Sur les îles tournées vers le Soleil, le jour se lève avant partout ailleurs. Le vent brûlant y souffle fort.",
|
||||
"coverCardId": "solar-dawn-capybara",
|
||||
"stats": ["endurance", "fortune", "bravoure", "orientation"],
|
||||
"conditions": [{ "type": "tag", "tag": "lieu:soleil" }],
|
||||
"dangers": [
|
||||
{ "id": "scorching-wind", "label": "Vent brûlant", "stat": "endurance", "unlessTags": ["personnage:loup"] },
|
||||
{ "id": "blinding-light", "label": "Lumière aveuglante", "stat": "orientation", "unlessTags": ["lieu:soleil"] }
|
||||
],
|
||||
"hidden": false
|
||||
},
|
||||
{
|
||||
"id": "comet-lakes",
|
||||
"name": "Les Lacs des Comètes",
|
||||
"description": "L'eau des îles est arrivée avec les comètes. Leurs lacs les plus anciens gardent des pierres aux reflets argentés.",
|
||||
"coverCardId": "cosmic-water-axolotl",
|
||||
"stats": ["fortune", "endurance", "orientation", "bravoure"],
|
||||
"conditions": [{ "type": "tag", "tag": "theme:eau" }],
|
||||
"dangers": [
|
||||
{ "id": "flash-flood", "label": "Crue soudaine", "stat": "fortune", "unlessTags": ["personnage:loutre"] },
|
||||
{ "id": "comet-tail", "label": "Queue de comète", "stat": "endurance", "unlessTags": ["theme:cometes"] }
|
||||
],
|
||||
"hidden": false
|
||||
},
|
||||
{
|
||||
"id": "great-void",
|
||||
"name": "Le Grand Vide",
|
||||
"description": "Entre les îles, le noir est profond et les repères rares. Les bateaux du ciel y voyagent lentement.",
|
||||
"coverCardId": "deep-sky-ray",
|
||||
"stats": ["orientation", "endurance", "bravoure", "fortune"],
|
||||
"conditions": [{ "type": "tag", "tag": "lieu:vide" }],
|
||||
"dangers": [
|
||||
{ "id": "void-mist", "label": "Brume du vide", "stat": "orientation", "unlessTags": ["theme:constellations"] },
|
||||
{ "id": "silent-dark", "label": "Noir silencieux", "stat": "endurance", "unlessTags": ["theme:nuit"] }
|
||||
],
|
||||
"hidden": false
|
||||
},
|
||||
{
|
||||
"id": "old-observatories",
|
||||
"name": "Les Vieux Observatoires",
|
||||
"description": "Les premiers observatoires des Veilleurs sont pleins de cartes, de carnets et d'instruments oubliés.",
|
||||
"coverCardId": "watchers-spyglass",
|
||||
"stats": ["orientation", "fortune", "endurance", "bravoure"],
|
||||
"conditions": [{ "type": "tag", "tag": "theme:veilleurs" }],
|
||||
"dangers": [
|
||||
{ "id": "starless-night", "label": "Nuit sans étoiles", "stat": "orientation", "unlessTags": ["personnage:hibou"] },
|
||||
{ "id": "crumbling-tower", "label": "Tour qui s'effrite", "stat": "fortune", "unlessTags": ["theme:veilleurs"] }
|
||||
],
|
||||
"hidden": false
|
||||
},
|
||||
{
|
||||
"id": "reunited-isles-feast",
|
||||
"name": "La Fête des Îles Réunies",
|
||||
"description": "Pendant la Longue Nuit, les îles se rapprochent pour la grande fête. Il y a des cadeaux à livrer dans tout l'archipel.",
|
||||
"coverCardId": "celestial-fox-mask",
|
||||
"stats": ["bravoure", "fortune", "orientation", "endurance"],
|
||||
"conditions": [{ "type": "tag", "tag": "theme:fete" }],
|
||||
"dangers": [
|
||||
{ "id": "feast-crowd", "label": "Foule du réveillon", "stat": "orientation", "unlessTags": ["theme:hiver"] },
|
||||
{ "id": "lost-gifts", "label": "Cadeaux égarés", "stat": "fortune", "unlessTags": ["theme:fete"] }
|
||||
],
|
||||
"hidden": false
|
||||
},
|
||||
{
|
||||
"id": "forgotten-ruins",
|
||||
"name": "Les Ruines Oubliées",
|
||||
"description": "Des temples rêvés se cachent sous la végétation des îles-jeux. Leurs pièges gardent toujours un trésor.",
|
||||
"coverCardId": "lost-ruins-meerkat",
|
||||
"stats": ["bravoure", "endurance", "orientation", "fortune"],
|
||||
"conditions": [{ "type": "tag", "tag": "theme:tresor" }],
|
||||
"dangers": [
|
||||
{ "id": "ancient-trap", "label": "Piège ancien", "stat": "endurance", "unlessTags": ["theme:aventure"] },
|
||||
{ "id": "maze-corridors", "label": "Couloirs en labyrinthe", "stat": "orientation", "unlessTags": ["personnage:herisson", "personnage:suricate"] }
|
||||
],
|
||||
"hidden": false
|
||||
},
|
||||
{
|
||||
"id": "pale-moon-slope",
|
||||
"name": "Le Versant de la Lune Pâle",
|
||||
"description": "Sous la Lune Pâle, les roches bleues brillent dans le noir. Il fait froid, mais on y voit loin.",
|
||||
"coverCardId": "pale-moon-owl",
|
||||
"stats": ["endurance", "orientation", "fortune", "bravoure"],
|
||||
"conditions": [{ "type": "tag", "tag": "theme:nuit" }],
|
||||
"dangers": [
|
||||
{ "id": "lunar-cold", "label": "Froid lunaire", "stat": "endurance", "unlessTags": ["lieu:glaces"] },
|
||||
{ "id": "veiled-moon", "label": "Lune voilée", "stat": "orientation", "unlessTags": ["lieu:lune-pale", "personnage:hibou"] }
|
||||
],
|
||||
"hidden": false
|
||||
}
|
||||
]
|
||||
|
|
@ -3,6 +3,7 @@ import { mkdirSync } from "node:fs";
|
|||
import { dirname } from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { INITIAL_COLLECTION_STATES, INITIAL_DROP_RATES, INITIAL_RECHARGE_SETTING, INITIAL_SHOP_SETTING } from "./admin-seed.js";
|
||||
import { DEFAULT_EXPEDITION_SETTINGS } from "./expedition-settings.js";
|
||||
|
||||
const MIGRATIONS = [
|
||||
`
|
||||
|
|
@ -219,6 +220,84 @@ const MIGRATIONS = [
|
|||
PRIMARY KEY (player_id, day)
|
||||
) STRICT;
|
||||
CREATE INDEX daily_attempts_day_idx ON daily_attempts(day, status);
|
||||
`,
|
||||
// Expéditions : Éclats d'étoile, réglages (un JSON validé par expedition-settings.js, Expéditions fermées au départ), destinations du jour,
|
||||
// expéditions, participants et places. Les CHECK prévoient déjà le groupe (mode, inscription, 5 ★, 4 places, rôles).
|
||||
// gift_packs est reconstruite : un paquet offert vient d'une campagne ou d'une expédition.
|
||||
`
|
||||
ALTER TABLE players ADD COLUMN eclats INTEGER NOT NULL DEFAULT 0 CHECK (eclats >= 0);
|
||||
CREATE TABLE expedition_settings (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
settings_json TEXT NOT NULL CHECK (json_valid(settings_json)),
|
||||
updated_at INTEGER NOT NULL,
|
||||
updated_by TEXT REFERENCES players(id)
|
||||
) STRICT;
|
||||
INSERT INTO expedition_settings(id, settings_json, updated_at, updated_by) VALUES (1, '${JSON.stringify(DEFAULT_EXPEDITION_SETTINGS)}', 0, NULL);
|
||||
-- draw_json : destinations tirées (identifiant, condition et dangers) ; les exigences chiffrées sont calculées à la lecture.
|
||||
CREATE TABLE expedition_days (
|
||||
day TEXT PRIMARY KEY,
|
||||
draw_json TEXT NOT NULL CHECK (json_valid(draw_json)),
|
||||
created_at INTEGER NOT NULL
|
||||
) STRICT;
|
||||
-- setup_json fige la destination, les exigences et les réglages du départ ; result_json n'est montré qu'au retour.
|
||||
CREATE TABLE expeditions (
|
||||
id TEXT PRIMARY KEY,
|
||||
mode TEXT NOT NULL CHECK (mode IN ('solo', 'group')),
|
||||
day TEXT NOT NULL REFERENCES expedition_days(day),
|
||||
destination_id TEXT NOT NULL,
|
||||
difficulty INTEGER NOT NULL CHECK (difficulty BETWEEN 1 AND 5),
|
||||
duration_ms INTEGER NOT NULL CHECK (duration_ms > 0),
|
||||
creator_id TEXT NOT NULL REFERENCES players(id),
|
||||
status TEXT NOT NULL CHECK (status IN ('forming', 'running', 'completed', 'cancelled')),
|
||||
setup_json TEXT NOT NULL CHECK (json_valid(setup_json)),
|
||||
result_json TEXT CHECK (result_json IS NULL OR json_valid(result_json)),
|
||||
created_at INTEGER NOT NULL,
|
||||
departs_at INTEGER,
|
||||
returns_at INTEGER,
|
||||
completed_at INTEGER
|
||||
) STRICT;
|
||||
CREATE INDEX expeditions_status_idx ON expeditions(status, returns_at);
|
||||
CREATE INDEX expeditions_day_idx ON expeditions(day, creator_id);
|
||||
CREATE TABLE expedition_members (
|
||||
expedition_id TEXT NOT NULL REFERENCES expeditions(id) ON DELETE CASCADE,
|
||||
player_id TEXT NOT NULL REFERENCES players(id),
|
||||
reward_json TEXT CHECK (reward_json IS NULL OR json_valid(reward_json)),
|
||||
joined_at INTEGER NOT NULL,
|
||||
claimed_at INTEGER,
|
||||
PRIMARY KEY (expedition_id, player_id)
|
||||
) STRICT;
|
||||
CREATE INDEX expedition_members_player_idx ON expedition_members(player_id, claimed_at);
|
||||
-- player_id nul : place tenue par le Veilleur de la Guilde, sans carte ni rôle.
|
||||
CREATE TABLE expedition_slots (
|
||||
expedition_id TEXT NOT NULL REFERENCES expeditions(id) ON DELETE CASCADE,
|
||||
position INTEGER NOT NULL CHECK (position BETWEEN 0 AND 3),
|
||||
role TEXT CHECK (role IS NULL OR role IN ('leader', 'guardian', 'seeker', 'navigator')),
|
||||
player_id TEXT REFERENCES players(id),
|
||||
edition_id TEXT,
|
||||
card_id TEXT,
|
||||
level INTEGER NOT NULL DEFAULT 0 CHECK (level >= 0),
|
||||
stats_json TEXT NOT NULL CHECK (json_valid(stats_json)),
|
||||
PRIMARY KEY (expedition_id, position)
|
||||
) STRICT;
|
||||
CREATE INDEX expedition_slots_player_idx ON expedition_slots(player_id, edition_id);
|
||||
CREATE TABLE gift_packs_next (
|
||||
id TEXT PRIMARY KEY,
|
||||
player_id TEXT NOT NULL REFERENCES players(id),
|
||||
source TEXT NOT NULL DEFAULT 'campaign' CHECK (source IN ('campaign', 'expedition')),
|
||||
campaign_id TEXT REFERENCES campaigns(id),
|
||||
expedition_id TEXT REFERENCES expeditions(id),
|
||||
collection_id TEXT NOT NULL,
|
||||
options_json TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
opening_id TEXT REFERENCES openings(id),
|
||||
opened_at INTEGER,
|
||||
CHECK ((source = 'campaign' AND campaign_id IS NOT NULL) OR (source = 'expedition' AND expedition_id IS NOT NULL))
|
||||
) STRICT;
|
||||
INSERT INTO gift_packs_next(id, player_id, source, campaign_id, collection_id, options_json, created_at, opening_id, opened_at)
|
||||
SELECT id, player_id, 'campaign', campaign_id, collection_id, options_json, created_at, opening_id, opened_at FROM gift_packs;
|
||||
DROP TABLE gift_packs;
|
||||
ALTER TABLE gift_packs_next RENAME TO gift_packs;
|
||||
CREATE INDEX gift_packs_player_idx ON gift_packs(player_id, opened_at);
|
||||
`
|
||||
];
|
||||
|
||||
|
|
|
|||
72
services/cards/expedition-content.js
Normal file
72
services/cards/expedition-content.js
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
// Rôle : charge et valide les destinations des Expéditions Sokko TCG, définies dans un fichier du serveur pour garder secrètes les destinations cachées.
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { cardExpeditionData, isExpeditionCard, STAT_IDS } from "./expedition-rules.js";
|
||||
|
||||
export const DEFAULT_DESTINATIONS_PATH = fileURLToPath(new URL("./content/expedition-destinations.json", import.meta.url));
|
||||
|
||||
const ID_PATTERN = /^[a-z0-9-]+$/;
|
||||
// Une condition ou un danger doit pouvoir être rempli par au moins ce nombre de cartes rare ou mieux.
|
||||
export const MIN_MATCHING_CARDS = 3;
|
||||
|
||||
function fail(destination, message) {
|
||||
throw new TypeError(`Expedition destination ${destination?.id ?? "?"}: ${message}`);
|
||||
}
|
||||
|
||||
// Cartes rare ou mieux qui portent une des étiquettes, ou qui appartiennent à la collection.
|
||||
function matchingCards(catalog, { tags = [], collectionId = null }) {
|
||||
return catalog.cards.filter((card) => {
|
||||
if (!isExpeditionCard(catalog, card.id)) return false;
|
||||
const data = cardExpeditionData(catalog, card.id);
|
||||
return collectionId ? data.collectionId === collectionId : data.tags.some((tag) => tags.includes(tag));
|
||||
});
|
||||
}
|
||||
|
||||
export function validateExpeditionDestinations(destinations, catalog) {
|
||||
if (!Array.isArray(destinations) || !destinations.length) throw new TypeError("Expedition destinations must be a non-empty array.");
|
||||
const tagIds = new Set(catalog.expeditionTags.map((tag) => tag.id));
|
||||
const collectionIds = new Set(catalog.collections.map((collection) => collection.id));
|
||||
const cardIds = new Set(catalog.cards.map((card) => card.id));
|
||||
const ids = new Set();
|
||||
for (const destination of destinations) {
|
||||
if (!ID_PATTERN.test(destination?.id ?? "")) fail(destination, "needs a lowercase id.");
|
||||
if (ids.has(destination.id)) fail(destination, "duplicate id.");
|
||||
ids.add(destination.id);
|
||||
if (typeof destination.name !== "string" || !destination.name || destination.name.length > 60) fail(destination, "name must contain 1 to 60 characters.");
|
||||
if (typeof destination.description !== "string" || !destination.description || destination.description.length > 200) fail(destination, "description must contain 1 to 200 characters.");
|
||||
if (destination.coverCardId != null && !cardIds.has(destination.coverCardId)) fail(destination, "unknown cover card.");
|
||||
if (typeof destination.hidden !== "boolean") fail(destination, "hidden must be a boolean.");
|
||||
if (!Array.isArray(destination.stats) || destination.stats.length !== STAT_IDS.length || new Set(destination.stats).size !== STAT_IDS.length
|
||||
|| destination.stats.some((stat) => !STAT_IDS.includes(stat))) {
|
||||
fail(destination, "stats must order the four stats.");
|
||||
}
|
||||
if (!Array.isArray(destination.conditions) || !destination.conditions.length) fail(destination, "needs at least one condition.");
|
||||
for (const condition of destination.conditions) {
|
||||
if (condition?.type === "tag") {
|
||||
if (!tagIds.has(condition.tag)) fail(destination, `unknown condition tag ${condition.tag}.`);
|
||||
if (matchingCards(catalog, { tags: [condition.tag] }).length < MIN_MATCHING_CARDS) fail(destination, `condition ${condition.tag} matches fewer than ${MIN_MATCHING_CARDS} rare or better cards.`);
|
||||
} else if (condition?.type === "collection") {
|
||||
if (!collectionIds.has(condition.collectionId)) fail(destination, `unknown condition collection ${condition.collectionId}.`);
|
||||
if (matchingCards(catalog, { collectionId: condition.collectionId }).length < MIN_MATCHING_CARDS) fail(destination, `condition ${condition.collectionId} matches fewer than ${MIN_MATCHING_CARDS} rare or better cards.`);
|
||||
} else {
|
||||
fail(destination, "condition type must be tag or collection.");
|
||||
}
|
||||
}
|
||||
if (!Array.isArray(destination.dangers) || !destination.dangers.length) fail(destination, "needs at least one danger.");
|
||||
const dangerIds = new Set();
|
||||
for (const danger of destination.dangers) {
|
||||
if (!ID_PATTERN.test(danger?.id ?? "") || dangerIds.has(danger.id)) fail(destination, "every danger needs a unique lowercase id.");
|
||||
dangerIds.add(danger.id);
|
||||
if (typeof danger.label !== "string" || !danger.label || danger.label.length > 40) fail(destination, `danger ${danger.id} label must contain 1 to 40 characters.`);
|
||||
if (!STAT_IDS.includes(danger.stat)) fail(destination, `danger ${danger.id} needs a known stat.`);
|
||||
if (!Array.isArray(danger.unlessTags) || !danger.unlessTags.length || danger.unlessTags.some((tag) => !tagIds.has(tag))) fail(destination, `danger ${danger.id} needs known counter tags.`);
|
||||
if (matchingCards(catalog, { tags: danger.unlessTags }).length < MIN_MATCHING_CARDS) fail(destination, `danger ${danger.id} can be countered by fewer than ${MIN_MATCHING_CARDS} rare or better cards.`);
|
||||
}
|
||||
}
|
||||
if (!destinations.some((destination) => !destination.hidden)) throw new TypeError("Expedition destinations need at least one visible destination.");
|
||||
return destinations;
|
||||
}
|
||||
|
||||
export function loadExpeditionDestinations(path, catalog) {
|
||||
return validateExpeditionDestinations(JSON.parse(readFileSync(path, "utf8")), catalog);
|
||||
}
|
||||
258
services/cards/expedition-rules.js
Normal file
258
services/cards/expedition-rules.js
Normal file
|
|
@ -0,0 +1,258 @@
|
|||
// Rôle : règles pures des Expéditions Sokko TCG (Puissance, stats, exigences par place, dangers, score, palier, butin, tirage du jour).
|
||||
// Aucune fonction ne lit la base ni l'horloge, et le hasard est toujours passé en paramètre : `random(max)` renvoie un entier dans [0, max).
|
||||
import { cardRarity } from "./daily.js";
|
||||
|
||||
export const STAT_IDS = Object.freeze(["bravoure", "endurance", "fortune", "orientation"]);
|
||||
// Rôle d'une place : il double la stat correspondante de la carte qui l'occupe.
|
||||
export const ROLE_BY_STAT = Object.freeze({ bravoure: "leader", endurance: "guardian", fortune: "seeker", orientation: "navigator" });
|
||||
export const STAT_BY_ROLE = Object.freeze(Object.fromEntries(Object.entries(ROLE_BY_STAT).map(([stat, role]) => [role, stat])));
|
||||
export const TIER_IDS = Object.freeze(["struggle", "success", "triumph"]);
|
||||
export const MAX_STARS = 5;
|
||||
// Nombre de stats exigées selon les étoiles : la 4e étoile ajoute un danger, la 5e la dernière stat et un second danger.
|
||||
const REQUIRED_STATS = Object.freeze([1, 2, 3, 3, 4]);
|
||||
const DANGER_COUNT = Object.freeze([0, 0, 0, 1, 2]);
|
||||
export const EXPEDITION_RARITIES = Object.freeze(["rare", "epic", "legendary", "mythic"]);
|
||||
|
||||
export const requiredStatCount = (stars) => REQUIRED_STATS[stars - 1];
|
||||
export const dangerCount = (stars) => DANGER_COUNT[stars - 1];
|
||||
export const hasCondition = (stars) => stars >= 3;
|
||||
|
||||
// Puissance d'une carte selon sa rareté et son niveau ; une commune n'en a pas (elle servira d'équipement).
|
||||
export function cardPower(rarity, level, settings) {
|
||||
const base = settings.power[rarity];
|
||||
if (!Number.isInteger(base)) return 0;
|
||||
return Math.min(settings.power.cap, base + Math.max(0, level) * settings.power.perLevel);
|
||||
}
|
||||
|
||||
// Niveau qui amène une rareté au plafond.
|
||||
export function maxLevel(rarity, settings) {
|
||||
const base = settings.power[rarity];
|
||||
if (!Number.isInteger(base) || base >= settings.power.cap) return 0;
|
||||
return Math.ceil((settings.power.cap - base) / settings.power.perLevel);
|
||||
}
|
||||
|
||||
// Répartit la Puissance selon le profil (pourcentages), au plus grand reste : la somme des stats vaut exactement la Puissance.
|
||||
export function splitPower(power, profile) {
|
||||
const raw = STAT_IDS.map((stat) => (power * profile[stat]) / 100);
|
||||
const stats = raw.map(Math.floor);
|
||||
let left = power - stats.reduce((sum, value) => sum + value, 0);
|
||||
const order = raw.map((value, index) => [value - Math.floor(value), index]).sort((a, b) => b[0] - a[0] || a[1] - b[1]);
|
||||
for (const [, index] of order) {
|
||||
if (left <= 0) break;
|
||||
stats[index] += 1;
|
||||
left -= 1;
|
||||
}
|
||||
return Object.fromEntries(STAT_IDS.map((stat, index) => [stat, stats[index]]));
|
||||
}
|
||||
|
||||
// Données d'expédition d'une carte : son profil (ou celui de sa collection), ses étiquettes et sa collection.
|
||||
export function cardExpeditionData(catalog, cardId) {
|
||||
const card = catalog.cards.find((item) => item.id === cardId);
|
||||
if (!card) return null;
|
||||
const collection = catalog.collections.find((item) => item.id === card.collectionId);
|
||||
return {
|
||||
cardId,
|
||||
collectionId: card.collectionId,
|
||||
tags: card.expedition?.tags || [],
|
||||
profile: card.expedition?.profile || collection?.expedition?.profile || null
|
||||
};
|
||||
}
|
||||
|
||||
// Ce qu'une édition apporte à une expédition : rareté de l'édition (une mythique garde la sienne), Puissance et stats.
|
||||
export function editionExpeditionData(catalog, editionId, level, settings) {
|
||||
const edition = catalog.editions.find((item) => item.id === editionId);
|
||||
if (!edition) return null;
|
||||
const data = cardExpeditionData(catalog, edition.cardId);
|
||||
if (!data?.profile || !EXPEDITION_RARITIES.includes(edition.rarity)) return null;
|
||||
const power = cardPower(edition.rarity, level, settings);
|
||||
return { ...data, editionId, rarity: edition.rarity, level, power, stats: splitPower(power, data.profile) };
|
||||
}
|
||||
|
||||
export const isExpeditionCard = (catalog, cardId) => EXPEDITION_RARITIES.includes(cardRarity(catalog, cardId));
|
||||
|
||||
// Rôles des places en solo : la destination fixe ceux de ses deux premières stats.
|
||||
export function soloRoles(destination, slotCount) {
|
||||
return destination.stats.slice(0, slotCount);
|
||||
}
|
||||
|
||||
// Exigence d'une stat = valeur par place × (nombre de places + places dont le rôle double cette stat).
|
||||
// Le solo et le groupe gardent ainsi le même rapport ; une place sans rôle (Veilleur de la Guilde) n'ajoute que sa part.
|
||||
export function requirementsFor(destination, stars, slotRoles, settings) {
|
||||
const perSlot = settings.requirements[`star${stars}`];
|
||||
return destination.stats.slice(0, requiredStatCount(stars)).map((stat, index) => ({
|
||||
stat,
|
||||
main: index === 0,
|
||||
value: perSlot[index] * (slotRoles.length + slotRoles.filter((role) => role === stat).length)
|
||||
}));
|
||||
}
|
||||
|
||||
// Somme des stats de l'équipe ; le rôle d'une place multiplie la stat correspondante de sa carte.
|
||||
export function teamStats(slots, settings) {
|
||||
const total = Object.fromEntries(STAT_IDS.map((stat) => [stat, 0]));
|
||||
for (const slot of slots) {
|
||||
for (const stat of STAT_IDS) {
|
||||
const multiplier = slot.role === stat ? settings.roles.multiplierPct / 100 : 1;
|
||||
total[stat] += (slot.stats?.[stat] || 0) * multiplier;
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
const slotMatches = (slot, condition) => (condition.type === "tag" ? slot.tags?.includes(condition.tag) : slot.collectionId === condition.collectionId);
|
||||
|
||||
export function conditionMet(slots, condition) {
|
||||
return slots.some((slot) => slotMatches(slot, condition));
|
||||
}
|
||||
|
||||
export function dangerCountered(slots, danger) {
|
||||
return slots.some((slot) => danger.unlessTags.some((tag) => slot.tags?.includes(tag)));
|
||||
}
|
||||
|
||||
// Malus de durée et dangers. L'Endurance de l'équipe (avant malus) efface le malus de durée et sert de bouclier contre un danger.
|
||||
export function applyHazards(stats, { slotCount, durationIndex, dangers = [] }, settings) {
|
||||
const endurance = stats.endurance;
|
||||
const result = { ...stats };
|
||||
const durationMalus = settings.durations.malusPct[durationIndex] / 100;
|
||||
const durationCover = Math.min(1, endurance / (settings.durations.endurancePerSlot * slotCount));
|
||||
const durationFactor = 1 - durationMalus * (1 - durationCover);
|
||||
for (const stat of STAT_IDS) result[stat] *= durationFactor;
|
||||
const shield = Math.min(1, endurance / (settings.danger.endurancePerSlot * slotCount)) * (settings.danger.shieldMaxPct / 100);
|
||||
const dangerFactor = 1 - (settings.danger.malusPct / 100) * (1 - shield);
|
||||
const appliedDangers = dangers.map((danger) => {
|
||||
if (!danger.countered) result[danger.stat] *= dangerFactor;
|
||||
return { ...danger, factor: danger.countered ? 1 : dangerFactor };
|
||||
});
|
||||
return { stats: result, durationFactor, dangers: appliedDangers };
|
||||
}
|
||||
|
||||
// Rendement d'une exigence : plein jusqu'à 100 %, puis réduit, jusqu'au plafond.
|
||||
export function efficiency(ratio, settings) {
|
||||
const over = Math.min(Math.max(ratio - 1, 0), settings.score.overflowSpanPct / 100);
|
||||
return Math.min(ratio, 1) + (settings.score.overflowPct / 100) * over;
|
||||
}
|
||||
|
||||
export function tierFor(scorePct, settings) {
|
||||
if (scorePct >= settings.score.triumphPct) return "triumph";
|
||||
if (scorePct >= settings.score.successPct) return "success";
|
||||
return "struggle";
|
||||
}
|
||||
|
||||
// Score de l'équipe : moyenne pondérée des rendements (stat principale plus lourde), condition, bonus de synergies, plafond.
|
||||
export function scoreExpedition({ requirements, stats, conditionMet: met = null, synergyPct = 0 }, settings) {
|
||||
let weighted = 0;
|
||||
let weights = 0;
|
||||
const perRequirement = requirements.map((requirement) => {
|
||||
const ratio = requirement.value > 0 ? stats[requirement.stat] / requirement.value : 1;
|
||||
const weight = requirement.main ? settings.score.mainWeight : settings.score.otherWeight;
|
||||
const value = efficiency(ratio, settings);
|
||||
weighted += value * weight;
|
||||
weights += weight;
|
||||
return { ...requirement, team: stats[requirement.stat], ratioPct: ratio * 100, efficiencyPct: value * 100 };
|
||||
});
|
||||
const conditionFactor = met === false ? 1 - settings.requirements.conditionMissPct / 100 : 1;
|
||||
const raw = (weights ? weighted / weights : 0) * 100 * conditionFactor * (1 + synergyPct / 100);
|
||||
const scorePct = Math.min(settings.score.capPct, raw);
|
||||
return { perRequirement, conditionFactor, scorePct, tier: tierFor(scorePct, settings) };
|
||||
}
|
||||
|
||||
function evaluateAt({ destination, entry, stars, durationIndex, slots }, base, settings) {
|
||||
const slotRoles = slots.map((slot) => slot.role ?? null);
|
||||
const requirements = requirementsFor(destination, stars, slotRoles, settings);
|
||||
const condition = hasCondition(stars) ? entry.condition : null;
|
||||
const dangers = (entry.dangers || []).slice(0, dangerCount(stars)).map((danger) => ({ ...danger, countered: dangerCountered(slots, danger) }));
|
||||
const hazards = applyHazards(base, { slotCount: slots.length, durationIndex, dangers }, settings);
|
||||
const met = condition ? conditionMet(slots, condition) : null;
|
||||
const score = scoreExpedition({ requirements, stats: hazards.stats, conditionMet: met }, settings);
|
||||
return { requirements, baseStats: base, stats: hazards.stats, durationFactor: hazards.durationFactor, dangers: hazards.dangers, condition, conditionMet: met, ...score };
|
||||
}
|
||||
|
||||
// Évalue une équipe sur une destination du jour : c'est le calcul complet du départ et de l'aperçu.
|
||||
// `slots` : [{ stats, role (stat doublée ou null), tags, collectionId }]. `entry` : { condition, dangers } de la destination du jour.
|
||||
// Une étoile de plus ne peut jamais améliorer le score : sans cette règle, une équipe faible sur la stat principale
|
||||
// gagnerait des points en ajoutant une stat où elle est forte. Le score retenu est donc le plus bas des niveaux 1 à `stars`.
|
||||
export function evaluateTeam(input, settings) {
|
||||
const base = teamStats(input.slots, settings);
|
||||
const result = evaluateAt(input, base, settings);
|
||||
let scorePct = result.scorePct;
|
||||
let limitedByStars = null;
|
||||
for (let stars = input.stars - 1; stars >= 1; stars -= 1) {
|
||||
const lower = evaluateAt({ ...input, stars }, base, settings).scorePct;
|
||||
if (lower < scorePct) {
|
||||
scorePct = lower;
|
||||
limitedByStars = stars;
|
||||
}
|
||||
}
|
||||
return { ...result, scorePct, limitedByStars, tier: tierFor(scorePct, settings) };
|
||||
}
|
||||
|
||||
// Butin espéré (valeurs fractionnaires) : il est proportionnel à la durée choisie, donc identique par heure.
|
||||
export function expectedLoot({ hours, stars, tier, fortune, slotCount, bonusSlot = null }, settings) {
|
||||
const { loot } = settings;
|
||||
const bonus = bonusSlot ? loot.bonusSlotPct[bonusSlot - 5] / 100 : 1;
|
||||
const base = hours * (loot.difficultyPct[stars - 1] / 100) * (loot.tierPct[TIER_IDS.indexOf(tier)] / 100) * bonus;
|
||||
const fortuneBonusPct = Math.min(loot.fortuneCapPct, (fortune / Math.max(1, slotCount)) * loot.fortunePerPointPct);
|
||||
return {
|
||||
eclats: base * (loot.eclatsPerHourCents / 100),
|
||||
stardust: base * (loot.stardustPerHourCents / 100),
|
||||
packs: Math.min(loot.maxPacks, base * (loot.packPerHourPermille / 1000) * (1 + fortuneBonusPct / 100)),
|
||||
fortuneBonusPct
|
||||
};
|
||||
}
|
||||
|
||||
// Arrondi aléatoire qui conserve la moyenne : partie entière, plus une unité avec la probabilité de la partie décimale.
|
||||
export function roundStochastic(value, random) {
|
||||
const whole = Math.floor(value);
|
||||
return whole + (random(1000) < Math.round((value - whole) * 1000) ? 1 : 0);
|
||||
}
|
||||
|
||||
export function rollLoot(expected, settings, random) {
|
||||
return {
|
||||
eclats: roundStochastic(expected.eclats, random),
|
||||
stardust: roundStochastic(expected.stardust, random),
|
||||
packs: Math.min(settings.loot.maxPacks, roundStochastic(expected.packs, random))
|
||||
};
|
||||
}
|
||||
|
||||
function weightedPick(entries, random) {
|
||||
const total = entries.reduce((sum, entry) => sum + entry.weight, 0);
|
||||
let cursor = random(total);
|
||||
for (const entry of entries) {
|
||||
cursor -= entry.weight;
|
||||
if (cursor < 0) return entry;
|
||||
}
|
||||
return entries.at(-1);
|
||||
}
|
||||
|
||||
// Destinations du jour : tirées selon leur poids parmi les destinations actives et non cachées, en évitant celles des jours précédents
|
||||
// tant qu'il en reste assez. Pour chacune : l'indice de sa condition et ceux de deux dangers (le second sert au 5 ★).
|
||||
export function drawExpeditionDay(destinations, settings, recentIds, random) {
|
||||
const candidates = destinations
|
||||
.filter((destination) => !destination.hidden)
|
||||
.map((destination) => ({ destination, ...(settings.destinations[destination.id] || { active: true, weight: 1 }) }))
|
||||
.filter((entry) => entry.active && entry.weight > 0);
|
||||
const count = Math.min(settings.day.destinationsPerDay, candidates.length);
|
||||
const recent = new Set(recentIds);
|
||||
const fresh = candidates.filter((entry) => !recent.has(entry.destination.id));
|
||||
let pool = fresh.length >= count ? fresh : candidates;
|
||||
const picked = [];
|
||||
while (picked.length < count && pool.length) {
|
||||
const entry = weightedPick(pool, random);
|
||||
picked.push(entry.destination);
|
||||
pool = pool.filter((item) => item !== entry);
|
||||
}
|
||||
return picked.map((destination) => {
|
||||
const first = random(destination.dangers.length);
|
||||
const second = destination.dangers.length > 1 ? (first + 1 + random(destination.dangers.length - 1)) % destination.dangers.length : first;
|
||||
return { destinationId: destination.id, conditionIndex: random(destination.conditions.length), dangerIndexes: [first, second] };
|
||||
});
|
||||
}
|
||||
|
||||
// Destination du jour prête à jouer : condition et dangers résolus. Null si la destination a disparu du contenu.
|
||||
export function resolveDayEntry(destinations, draw) {
|
||||
const destination = destinations.find((item) => item.id === draw.destinationId);
|
||||
if (!destination) return null;
|
||||
const condition = destination.conditions[draw.conditionIndex] || destination.conditions[0];
|
||||
const indexes = [...new Set(draw.dangerIndexes)];
|
||||
const dangers = indexes.map((index) => destination.dangers[index]).filter(Boolean);
|
||||
return { destination, entry: { condition, dangers } };
|
||||
}
|
||||
384
services/cards/expedition-service.js
Normal file
384
services/cards/expedition-service.js
Normal file
|
|
@ -0,0 +1,384 @@
|
|||
// Rôle : applique les règles des Expéditions Sokko TCG avec la base (destinations du jour, départ solo, retour, réglages d'administration).
|
||||
// Branché sur CardsService (`service.expeditions`) : il réutilise sa base, son horloge, son hasard, son audit et sa collection.
|
||||
import { randomInt, randomUUID } from "node:crypto";
|
||||
import { dailyDayKey, nextDailyAt, shiftDayKey } from "./daily.js";
|
||||
import {
|
||||
dangerCount, drawExpeditionDay, editionExpeditionData, evaluateTeam, expectedLoot, hasCondition, MAX_STARS, requirementsFor, resolveDayEntry,
|
||||
ROLE_BY_STAT, rollLoot, soloRoles, STAT_BY_ROLE
|
||||
} from "./expedition-rules.js";
|
||||
import {
|
||||
DEFAULT_EXPEDITION_SETTINGS, diffExpeditionSettings, EXPEDITION_SETTINGS_SCHEMA, mergeExpeditionSettings, validateExpeditionSettings
|
||||
} from "./expedition-settings.js";
|
||||
|
||||
const HOUR_MS = 3_600_000;
|
||||
|
||||
function fail(status, code, message) {
|
||||
throw Object.assign(new Error(message), { status, code });
|
||||
}
|
||||
|
||||
const parse = (value) => (value == null ? null : JSON.parse(value));
|
||||
const round1 = (value) => Math.round(value * 10) / 10;
|
||||
|
||||
export class ExpeditionService {
|
||||
constructor(cards, destinations) {
|
||||
this.cards = cards;
|
||||
this.db = cards.db;
|
||||
this.destinations = destinations;
|
||||
this.destinationIds = destinations.map((destination) => destination.id);
|
||||
}
|
||||
|
||||
now() {
|
||||
return this.cards.now();
|
||||
}
|
||||
|
||||
random(max) {
|
||||
return this.cards.random ? this.cards.random(max) : randomInt(max);
|
||||
}
|
||||
|
||||
// Réglages en vigueur : un champ stocké invalide reprend sa valeur par défaut, pour que le jeu reste jouable.
|
||||
get settings() {
|
||||
const row = this.db.prepare("SELECT settings_json FROM expedition_settings WHERE id = 1").get();
|
||||
return mergeExpeditionSettings(parse(row?.settings_json) || {}, this.destinationIds, (path) => console.error(`Invalid stored expedition setting ${path}; using its default.`));
|
||||
}
|
||||
|
||||
settingsUpdatedAt() {
|
||||
return this.db.prepare("SELECT updated_at FROM expedition_settings WHERE id = 1").get()?.updated_at ?? 0;
|
||||
}
|
||||
|
||||
updateSettings(adminId, settings) {
|
||||
this.cards.requireAdmin(adminId);
|
||||
const error = validateExpeditionSettings(settings, this.destinationIds);
|
||||
if (error) fail(400, "EXPEDITION_SETTINGS_INVALID", error);
|
||||
const previous = this.settings;
|
||||
const next = mergeExpeditionSettings(settings, this.destinationIds);
|
||||
const changes = diffExpeditionSettings(previous, next);
|
||||
if (!changes.length) fail(409, "EXPEDITION_SETTINGS_UNCHANGED", "Ces réglages sont déjà en vigueur.");
|
||||
this.cards.database.transaction(() => {
|
||||
this.db.prepare("UPDATE expedition_settings SET settings_json = ?, updated_at = ?, updated_by = ? WHERE id = 1").run(JSON.stringify(next), this.now(), adminId);
|
||||
this.cards.audit(adminId, "expedition_settings_updated", "expeditions", { changes });
|
||||
});
|
||||
return { expeditionSettings: this.adminSettings() };
|
||||
}
|
||||
|
||||
// Ce que l'administration affiche et modifie : réglages, valeurs par défaut, bornes et destinations (définies côté serveur).
|
||||
adminSettings() {
|
||||
return {
|
||||
settings: this.settings,
|
||||
defaults: mergeExpeditionSettings(DEFAULT_EXPEDITION_SETTINGS, this.destinationIds),
|
||||
schema: EXPEDITION_SETTINGS_SCHEMA,
|
||||
destinations: this.destinations.map((destination) => ({ id: destination.id, name: destination.name, hidden: destination.hidden })),
|
||||
updatedAt: this.settingsUpdatedAt()
|
||||
};
|
||||
}
|
||||
|
||||
// Destinations du jour, tirées au premier appel du jour de Paris. À appeler dans une transaction.
|
||||
ensureDay(day, settings) {
|
||||
const stored = () => this.db.prepare("SELECT draw_json FROM expedition_days WHERE day = ?").get(day);
|
||||
if (!stored()) {
|
||||
const recentDays = settings.day.avoidRepeatDays ? this.db.prepare("SELECT draw_json FROM expedition_days WHERE day >= ? AND day < ?").all(shiftDayKey(day, -settings.day.avoidRepeatDays), day) : [];
|
||||
const recent = recentDays.flatMap((row) => JSON.parse(row.draw_json).map((entry) => entry.destinationId));
|
||||
const draw = drawExpeditionDay(this.destinations, settings, recent, (max) => this.random(max));
|
||||
if (!draw.length) fail(409, "EXPEDITIONS_UNAVAILABLE", "Aucune destination n’est ouverte aujourd’hui.");
|
||||
this.db.prepare("INSERT INTO expedition_days(day, draw_json, created_at) VALUES (?, ?, ?)").run(day, JSON.stringify(draw), this.now());
|
||||
}
|
||||
// Une destination retirée du contenu après le tirage disparaît simplement de la liste du jour.
|
||||
return JSON.parse(stored().draw_json).map((draw) => resolveDayEntry(this.destinations, draw)).filter(Boolean);
|
||||
}
|
||||
|
||||
today(settings) {
|
||||
const day = dailyDayKey(this.now());
|
||||
return { day, entries: this.cards.database.transaction(() => this.ensureDay(day, settings)) };
|
||||
}
|
||||
|
||||
// Éditions occupées : celles d'une expédition en route dont le butin n'a pas encore été récupéré par leur propriétaire.
|
||||
busyEditions(playerId) {
|
||||
return new Map(this.db.prepare(`SELECT s.edition_id, e.id, e.returns_at FROM expedition_slots s
|
||||
JOIN expeditions e ON e.id = s.expedition_id
|
||||
JOIN expedition_members m ON m.expedition_id = e.id AND m.player_id = s.player_id
|
||||
WHERE s.player_id = ? AND e.status = 'running' AND m.claimed_at IS NULL AND s.edition_id IS NOT NULL`).all(playerId)
|
||||
.map((row) => [row.edition_id, { expeditionId: row.id, returnsAt: row.returns_at }]));
|
||||
}
|
||||
|
||||
// Cartes du joueur jouables en expédition (rare ou mieux, révélées), avec leur Puissance et leurs stats.
|
||||
eligibleCards(playerId, settings) {
|
||||
const pending = this.db.prepare("SELECT id FROM openings WHERE player_id = ? AND status = 'pending' LIMIT 1").get(playerId);
|
||||
const busy = this.busyEditions(playerId);
|
||||
return this.cards.visibleCollection(playerId, pending?.id).map((entry) => {
|
||||
const data = editionExpeditionData(this.cards.catalog, entry.editionId, 0, settings);
|
||||
if (!data) return null;
|
||||
const busyEntry = busy.get(entry.editionId);
|
||||
return { ...data, busy: Boolean(busyEntry), busyUntil: busyEntry?.returnsAt ?? null };
|
||||
}).filter(Boolean);
|
||||
}
|
||||
|
||||
activeCount(playerId, mode) {
|
||||
return this.db.prepare(`SELECT COUNT(*) AS count FROM expeditions e JOIN expedition_members m ON m.expedition_id = e.id
|
||||
WHERE m.player_id = ? AND e.mode = ? AND e.status = 'running' AND m.claimed_at IS NULL`).get(playerId, mode).count;
|
||||
}
|
||||
|
||||
// Destination du jour vue par le joueur : rôles du solo et exigences chiffrées pour chaque étoile autorisée.
|
||||
destinationView({ destination, entry }, settings) {
|
||||
const roles = soloRoles(destination, settings.solo.cards);
|
||||
const stars = {};
|
||||
for (let star = settings.solo.minStars; star <= settings.solo.maxStars; star += 1) {
|
||||
stars[star] = {
|
||||
requirements: requirementsFor(destination, star, roles, settings),
|
||||
condition: hasCondition(star) ? entry.condition : null,
|
||||
dangers: entry.dangers.slice(0, dangerCount(star))
|
||||
};
|
||||
}
|
||||
return { id: destination.id, name: destination.name, description: destination.description, coverCardId: destination.coverCardId ?? null, stats: destination.stats, roles, stars };
|
||||
}
|
||||
|
||||
// Valide une équipe solo et calcule son résultat (sans écriture) : base commune de l'aperçu et du départ.
|
||||
// `today` : { day, entries }, les destinations du jour, lues par l'appelant (dans sa transaction pour un départ).
|
||||
prepareSolo(playerId, body, settings, today) {
|
||||
if (!settings.enabled) fail(409, "EXPEDITIONS_CLOSED", "Les Expéditions sont fermées pour le moment.");
|
||||
const { day, entries } = today;
|
||||
if (body?.day !== day) fail(409, "EXPEDITION_DAY_EXPIRED", "Les destinations ont changé : rechargez les Expéditions du jour.");
|
||||
const resolved = entries.find((item) => item.destination.id === body.destinationId);
|
||||
if (!resolved) fail(400, "EXPEDITION_INVALID", "Cette destination n’est pas proposée aujourd’hui.");
|
||||
const stars = body.difficulty;
|
||||
if (!Number.isInteger(stars) || stars < settings.solo.minStars || stars > settings.solo.maxStars) fail(400, "EXPEDITION_INVALID", "Difficulté invalide.");
|
||||
const durationIndex = settings.durations.hours.indexOf(body.durationHours);
|
||||
if (durationIndex < 0) fail(400, "EXPEDITION_INVALID", "Durée invalide.");
|
||||
const editionIds = body.slots;
|
||||
if (!Array.isArray(editionIds) || editionIds.length !== settings.solo.cards || editionIds.some((id) => typeof id !== "string")) {
|
||||
fail(400, "EXPEDITION_CARD_INVALID", `Choisissez ${settings.solo.cards} cartes.`);
|
||||
}
|
||||
const owned = new Map(this.eligibleCards(playerId, settings).map((card) => [card.editionId, card]));
|
||||
const roles = soloRoles(resolved.destination, settings.solo.cards);
|
||||
const slots = editionIds.map((editionId, position) => {
|
||||
const data = editionExpeditionData(this.cards.catalog, editionId, 0, settings);
|
||||
if (!data) fail(400, "EXPEDITION_CARD_INVALID", "Seules les cartes rares, épiques, légendaires et mythiques partent en expédition.");
|
||||
const card = owned.get(editionId);
|
||||
if (!card) fail(404, "CARD_NOT_OWNED", "Vous ne possédez pas cette carte.");
|
||||
return { ...card, role: roles[position], position };
|
||||
});
|
||||
if (new Set(slots.map((slot) => slot.cardId)).size !== slots.length) fail(400, "EXPEDITION_CARD_INVALID", "Une même carte ne peut occuper qu’une place.");
|
||||
const evaluation = evaluateTeam({ destination: resolved.destination, entry: resolved.entry, stars, durationIndex, slots }, settings);
|
||||
const hours = settings.durations.hours[durationIndex];
|
||||
const expected = expectedLoot({ hours, stars, tier: evaluation.tier, fortune: evaluation.stats.fortune, slotCount: slots.length }, settings);
|
||||
return { day, resolved, stars, durationIndex, hours, slots, evaluation, expected };
|
||||
}
|
||||
|
||||
resultView(evaluation) {
|
||||
return {
|
||||
scorePct: round1(evaluation.scorePct),
|
||||
tier: evaluation.tier,
|
||||
limitedByStars: evaluation.limitedByStars,
|
||||
conditionMet: evaluation.conditionMet,
|
||||
durationFactor: evaluation.durationFactor,
|
||||
stats: Object.fromEntries(Object.entries(evaluation.stats).map(([stat, value]) => [stat, round1(value)])),
|
||||
requirements: evaluation.perRequirement.map((item) => ({ stat: item.stat, main: item.main, value: item.value, team: round1(item.team), ratioPct: round1(item.ratioPct) })),
|
||||
dangers: evaluation.dangers.map((danger) => ({ id: danger.id, label: danger.label, stat: danger.stat, unlessTags: danger.unlessTags, countered: danger.countered }))
|
||||
};
|
||||
}
|
||||
|
||||
preview(playerId, body) {
|
||||
const settings = this.settings;
|
||||
if (!settings.enabled) fail(409, "EXPEDITIONS_CLOSED", "Les Expéditions sont fermées pour le moment.");
|
||||
const plan = this.prepareSolo(playerId, body, settings, this.today(settings));
|
||||
return {
|
||||
preview: {
|
||||
...this.resultView(plan.evaluation),
|
||||
expected: { eclats: round1(plan.expected.eclats), stardust: round1(plan.expected.stardust), packChancePct: round1(Math.min(1, plan.expected.packs) * 100), fortuneBonusPct: round1(plan.expected.fortuneBonusPct) }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Collection d'un paquet rapporté : une collection permanente ouverte, au hasard.
|
||||
packCollection() {
|
||||
const collections = this.cards.catalog.collections.filter((collection) => collection.active && collection.packCategory === "permanent" && collection.dropWeights);
|
||||
return collections.length ? collections[this.random(collections.length)].id : null;
|
||||
}
|
||||
|
||||
startSolo(playerId, body, requestKey) {
|
||||
if (!requestKey || requestKey.length > 100) fail(400, "IDEMPOTENCY_REQUIRED", "Une clé d'idempotence est requise.");
|
||||
const settings = this.settings;
|
||||
let expeditionId;
|
||||
this.cards.database.transaction(() => {
|
||||
const previous = this.db.prepare("SELECT response_json FROM idempotency WHERE player_id = ? AND scope = 'expedition-start' AND request_key = ?").get(playerId, requestKey);
|
||||
if (previous) {
|
||||
expeditionId = JSON.parse(previous.response_json).expeditionId;
|
||||
return;
|
||||
}
|
||||
if (!settings.enabled) fail(409, "EXPEDITIONS_CLOSED", "Les Expéditions sont fermées pour le moment.");
|
||||
const day = dailyDayKey(this.now());
|
||||
const plan = this.prepareSolo(playerId, body, settings, { day, entries: this.ensureDay(day, settings) });
|
||||
const busy = plan.slots.find((slot) => slot.busy);
|
||||
if (busy) fail(409, "EXPEDITION_CARD_BUSY", "Cette carte est déjà en expédition.");
|
||||
if (this.activeCount(playerId, "solo") >= settings.solo.maxConcurrent) fail(409, "EXPEDITION_LIMIT", "Récupérez d’abord le butin de votre expédition en cours.");
|
||||
const now = this.now();
|
||||
const loot = rollLoot(plan.expected, settings, (max) => this.random(max));
|
||||
const packs = [];
|
||||
for (let index = 0; index < loot.packs; index += 1) {
|
||||
const collectionId = this.packCollection();
|
||||
if (collectionId) packs.push(collectionId);
|
||||
}
|
||||
const { destination } = plan.resolved;
|
||||
const setup = {
|
||||
destination: { id: destination.id, name: destination.name, description: destination.description, coverCardId: destination.coverCardId ?? null, stats: destination.stats },
|
||||
condition: plan.evaluation.condition,
|
||||
stars: plan.stars,
|
||||
hours: plan.hours,
|
||||
bonusSlot: null,
|
||||
roles: plan.slots.map((slot) => slot.role)
|
||||
};
|
||||
expeditionId = randomUUID();
|
||||
this.db.prepare(`INSERT INTO expeditions(id, mode, day, destination_id, difficulty, duration_ms, creator_id, status, setup_json, result_json, created_at, departs_at, returns_at)
|
||||
VALUES (?, 'solo', ?, ?, ?, ?, ?, 'running', ?, ?, ?, ?, ?)`)
|
||||
.run(expeditionId, plan.day, destination.id, plan.stars, plan.hours * HOUR_MS, playerId, JSON.stringify(setup), JSON.stringify(this.resultView(plan.evaluation)), now, now, now + plan.hours * HOUR_MS);
|
||||
this.db.prepare("INSERT INTO expedition_members(expedition_id, player_id, reward_json, joined_at) VALUES (?, ?, ?, ?)")
|
||||
.run(expeditionId, playerId, JSON.stringify({ eclats: loot.eclats, stardust: loot.stardust, packs }), now);
|
||||
const insertSlot = this.db.prepare("INSERT INTO expedition_slots(expedition_id, position, role, player_id, edition_id, card_id, level, stats_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
|
||||
for (const slot of plan.slots) insertSlot.run(expeditionId, slot.position, ROLE_BY_STAT[slot.role] ?? null, playerId, slot.editionId, slot.cardId, slot.level, JSON.stringify(slot.stats));
|
||||
this.db.prepare("INSERT INTO idempotency(player_id, scope, request_key, response_json, created_at) VALUES (?, 'expedition-start', ?, ?, ?)")
|
||||
.run(playerId, requestKey, JSON.stringify({ expeditionId }), now);
|
||||
});
|
||||
return { expedition: this.expeditionView(expeditionId, playerId), expeditions: this.getExpeditions(playerId), state: this.cards.getState(playerId) };
|
||||
}
|
||||
|
||||
// Vue d'une expédition pour un participant : le résultat et le butin n'apparaissent qu'au retour.
|
||||
expeditionView(expeditionId, playerId) {
|
||||
const row = this.db.prepare(`SELECT e.*, m.reward_json, m.claimed_at FROM expeditions e
|
||||
JOIN expedition_members m ON m.expedition_id = e.id AND m.player_id = ? WHERE e.id = ?`).get(playerId, expeditionId);
|
||||
if (!row) return null;
|
||||
const now = this.now();
|
||||
const returned = row.status === "completed" || (row.status === "running" && row.returns_at <= now);
|
||||
const status = row.status === "running" ? (returned ? "returned" : "running") : row.status;
|
||||
const setup = JSON.parse(row.setup_json);
|
||||
const slots = this.db.prepare("SELECT position, role, player_id, edition_id, card_id, level, stats_json FROM expedition_slots WHERE expedition_id = ? ORDER BY position").all(row.id)
|
||||
.map((slot) => ({
|
||||
position: slot.position, role: slot.role ? STAT_BY_ROLE[slot.role] : null, own: slot.player_id === playerId,
|
||||
editionId: slot.edition_id, cardId: slot.card_id, level: slot.level, stats: JSON.parse(slot.stats_json)
|
||||
}));
|
||||
return {
|
||||
id: row.id, mode: row.mode, status, day: row.day, destination: setup.destination, condition: setup.condition, stars: row.difficulty, hours: setup.hours,
|
||||
departsAt: row.departs_at, returnsAt: row.returns_at, claimedAt: row.claimed_at, slots,
|
||||
result: returned ? parse(row.result_json) : null,
|
||||
reward: returned ? parse(row.reward_json) : null
|
||||
};
|
||||
}
|
||||
|
||||
// Expéditions à suivre : en route, revenues sans butin récupéré, ou rentrées dans les dernières 24 heures.
|
||||
playerExpeditionIds(playerId) {
|
||||
const since = this.now() - 24 * HOUR_MS;
|
||||
return this.db.prepare(`SELECT e.id FROM expeditions e JOIN expedition_members m ON m.expedition_id = e.id
|
||||
WHERE m.player_id = ? AND ((e.status = 'running' AND m.claimed_at IS NULL) OR m.claimed_at >= ? OR (e.status = 'cancelled' AND e.completed_at >= ?))
|
||||
ORDER BY e.created_at DESC LIMIT 10`).all(playerId, since, since).map((row) => row.id);
|
||||
}
|
||||
|
||||
getExpeditions(playerId) {
|
||||
const settings = this.settings;
|
||||
const now = this.now();
|
||||
const base = {
|
||||
enabled: settings.enabled,
|
||||
nextDayAt: nextDailyAt(now),
|
||||
durations: settings.durations.hours,
|
||||
stars: { min: settings.solo.minStars, max: settings.solo.maxStars, limit: MAX_STARS },
|
||||
soloCards: settings.solo.cards,
|
||||
soloLimit: settings.solo.maxConcurrent,
|
||||
expeditions: this.playerExpeditionIds(playerId).map((id) => this.expeditionView(id, playerId))
|
||||
};
|
||||
// Fermées : le joueur peut encore récupérer le butin de ses expéditions, mais aucune destination n'est tirée.
|
||||
if (!settings.enabled) return { ...base, day: dailyDayKey(now), destinations: [], cards: [] };
|
||||
const { day, entries } = this.today(settings);
|
||||
return { ...base, day, destinations: entries.map((entry) => this.destinationView(entry, settings)), cards: this.eligibleCards(playerId, settings) };
|
||||
}
|
||||
|
||||
claim(playerId, expeditionId) {
|
||||
this.cards.database.transaction(() => {
|
||||
const row = this.db.prepare(`SELECT e.*, m.reward_json, m.claimed_at FROM expeditions e
|
||||
JOIN expedition_members m ON m.expedition_id = e.id AND m.player_id = ? WHERE e.id = ?`).get(playerId, expeditionId);
|
||||
if (!row || row.status === "cancelled") fail(404, "EXPEDITION_NOT_FOUND", "Cette expédition n’existe pas.");
|
||||
// Déjà récupéré : on renvoie le même rapport.
|
||||
if (row.claimed_at != null) return;
|
||||
const now = this.now();
|
||||
if (row.status !== "running" || row.returns_at > now) fail(409, "EXPEDITION_NOT_RETURNED", "Cette expédition n’est pas encore rentrée.");
|
||||
const reward = JSON.parse(row.reward_json);
|
||||
const setup = JSON.parse(row.setup_json);
|
||||
const result = JSON.parse(row.result_json);
|
||||
this.db.prepare("UPDATE players SET eclats = eclats + ?, stardust = stardust + ? WHERE id = ?").run(reward.eclats, reward.stardust, playerId);
|
||||
const insertPack = this.db.prepare("INSERT INTO gift_packs(id, player_id, source, expedition_id, collection_id, options_json, created_at) VALUES (?, ?, 'expedition', ?, ?, ?, ?)");
|
||||
for (const collectionId of reward.packs) insertPack.run(randomUUID(), playerId, row.id, collectionId, JSON.stringify({ rarityWeights: null, guarantee: null }), now);
|
||||
this.db.prepare("UPDATE expedition_members SET claimed_at = ? WHERE expedition_id = ? AND player_id = ?").run(now, row.id, playerId);
|
||||
const waiting = this.db.prepare("SELECT COUNT(*) AS count FROM expedition_members WHERE expedition_id = ? AND claimed_at IS NULL").get(row.id).count;
|
||||
if (!waiting) this.db.prepare("UPDATE expeditions SET status = 'completed', completed_at = ? WHERE id = ?").run(now, row.id);
|
||||
const editionIds = this.db.prepare("SELECT edition_id FROM expedition_slots WHERE expedition_id = ? AND player_id = ? ORDER BY position").all(row.id, playerId).map((slot) => slot.edition_id);
|
||||
this.cards.audit(playerId, "expedition_completed", row.id, {
|
||||
destinationId: setup.destination.id, destinationName: setup.destination.name, difficulty: row.difficulty, hours: setup.hours,
|
||||
tier: result.tier, scorePct: result.scorePct, eclats: reward.eclats, stardust: reward.stardust, packs: reward.packs.length, editionIds
|
||||
});
|
||||
});
|
||||
return { expedition: this.expeditionView(expeditionId, playerId), expeditions: this.getExpeditions(playerId), state: this.cards.getState(playerId) };
|
||||
}
|
||||
|
||||
// Annulation par un administrateur : les cartes sont libérées, sans butin.
|
||||
cancel(adminId, expeditionId) {
|
||||
this.cards.requireAdmin(adminId);
|
||||
this.cards.database.transaction(() => {
|
||||
const row = this.db.prepare("SELECT * FROM expeditions WHERE id = ?").get(expeditionId);
|
||||
if (!row) fail(404, "EXPEDITION_NOT_FOUND", "Cette expédition n’existe pas.");
|
||||
if (!["forming", "running"].includes(row.status)) fail(409, "EXPEDITION_FINISHED", "Cette expédition est déjà terminée.");
|
||||
this.cancelRow(row);
|
||||
this.cards.audit(adminId, "expedition_cancelled", row.id, { destinationId: row.destination_id, mode: row.mode, creatorId: row.creator_id });
|
||||
});
|
||||
return { expeditionsToday: this.adminSummary() };
|
||||
}
|
||||
|
||||
// Annule une expédition et prévient ceux qui n'avaient pas encore récupéré leur butin.
|
||||
cancelRow(row, { notify = true } = {}) {
|
||||
this.db.prepare("UPDATE expeditions SET status = 'cancelled', completed_at = ? WHERE id = ?").run(this.now(), row.id);
|
||||
if (!notify) return;
|
||||
const setup = JSON.parse(row.setup_json);
|
||||
for (const member of this.db.prepare("SELECT player_id FROM expedition_members WHERE expedition_id = ? AND claimed_at IS NULL").all(row.id)) {
|
||||
this.cards.audit(member.player_id, "expedition_cancelled_by_guild", row.id, { destinationId: setup.destination.id, destinationName: setup.destination.name });
|
||||
}
|
||||
}
|
||||
|
||||
// Suppression du compte : ses expéditions en cours sont annulées (ses cartes n'existent plus).
|
||||
forgetPlayer(playerId) {
|
||||
const rows = this.db.prepare(`SELECT e.* FROM expeditions e JOIN expedition_members m ON m.expedition_id = e.id
|
||||
WHERE m.player_id = ? AND e.status IN ('forming', 'running') AND m.claimed_at IS NULL`).all(playerId);
|
||||
for (const row of rows) this.cancelRow(row, { notify: false });
|
||||
}
|
||||
|
||||
// Résumé pour l'état du joueur (tuile de la Guilde, fiche de carte), sans tirer les destinations du jour.
|
||||
summary(playerId) {
|
||||
const settings = this.settings;
|
||||
const now = this.now();
|
||||
const active = this.db.prepare(`SELECT e.returns_at FROM expeditions e JOIN expedition_members m ON m.expedition_id = e.id
|
||||
WHERE m.player_id = ? AND e.status = 'running' AND m.claimed_at IS NULL`).all(playerId);
|
||||
const running = active.filter((row) => row.returns_at > now);
|
||||
const launchedToday = Boolean(this.db.prepare("SELECT 1 FROM expeditions WHERE creator_id = ? AND day = ? AND status != 'cancelled' LIMIT 1").get(playerId, dailyDayKey(now)));
|
||||
const busy = this.busyEditions(playerId);
|
||||
const eligibleCards = new Set(this.cards.collectionOf(playerId)
|
||||
.map((entry) => editionExpeditionData(this.cards.catalog, entry.editionId, 0, settings)?.cardId).filter(Boolean));
|
||||
return {
|
||||
enabled: settings.enabled,
|
||||
running: running.length,
|
||||
returned: active.length - running.length,
|
||||
nextReturnAt: running.length ? Math.min(...running.map((row) => row.returns_at)) : null,
|
||||
launchedToday,
|
||||
eligible: eligibleCards.size,
|
||||
soloCards: settings.solo.cards,
|
||||
busyEditions: [...busy].map(([editionId, entry]) => ({ editionId, returnsAt: entry.returnsAt }))
|
||||
};
|
||||
}
|
||||
|
||||
adminSummary() {
|
||||
const now = this.now();
|
||||
const day = dailyDayKey(now);
|
||||
return {
|
||||
day,
|
||||
launches: this.db.prepare("SELECT COUNT(*) AS count FROM expeditions WHERE day = ? AND status != 'forming'").get(day).count,
|
||||
running: this.db.prepare("SELECT COUNT(*) AS count FROM expeditions WHERE status = 'running' AND returns_at > ?").get(now).count,
|
||||
returnedUnclaimed: this.db.prepare(`SELECT COUNT(*) AS count FROM expedition_members m JOIN expeditions e ON e.id = m.expedition_id
|
||||
WHERE e.status = 'running' AND e.returns_at <= ? AND m.claimed_at IS NULL`).get(now).count,
|
||||
runningList: this.db.prepare(`SELECT e.id, e.destination_id, e.difficulty, e.returns_at, p.display_name FROM expeditions e JOIN players p ON p.id = e.creator_id
|
||||
WHERE e.status = 'running' ORDER BY e.returns_at LIMIT 20`).all()
|
||||
.map((row) => ({ id: row.id, destinationId: row.destination_id, stars: row.difficulty, returnsAt: row.returns_at, creatorName: row.display_name }))
|
||||
};
|
||||
}
|
||||
}
|
||||
172
services/cards/expedition-settings.js
Normal file
172
services/cards/expedition-settings.js
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
// Rôle : valeurs par défaut, bornes, fusion, validation et différences des réglages des Expéditions Sokko TCG.
|
||||
// Règles pures : aucune lecture de la base ni de l'horloge. Le schéma est la seule source des bornes, pour le serveur comme pour l'administration.
|
||||
|
||||
// Valeurs du document de conception. Une clé ajoutée plus tard prend sa valeur par défaut à la fusion, sans migration.
|
||||
export const DEFAULT_EXPEDITION_SETTINGS = Object.freeze({
|
||||
enabled: false,
|
||||
day: { destinationsPerDay: 4, avoidRepeatDays: 1 },
|
||||
durations: { hours: [2, 6, 12], malusPct: [0, 0, 15], endurancePerSlot: 12 },
|
||||
solo: { maxConcurrent: 1, cards: 2, minStars: 1, maxStars: 4 },
|
||||
power: { rare: 40, epic: 55, legendary: 70, mythic: 85, perLevel: 5, cap: 100 },
|
||||
roles: { multiplierPct: 200 },
|
||||
// Exigence d'une stat, par place, pour chaque nombre d'étoiles : stat principale, puis seconde, troisième et quatrième.
|
||||
requirements: { star1: [9], star2: [11, 10], star3: [15, 14, 11], star4: [19, 18, 14], star5: [22, 21, 17, 14], conditionMissPct: 25 },
|
||||
danger: { malusPct: 20, shieldMaxPct: 50, endurancePerSlot: 14 },
|
||||
score: { mainWeight: 2, otherWeight: 1, overflowPct: 50, overflowSpanPct: 100, capPct: 150, successPct: 80, triumphPct: 120 },
|
||||
loot: {
|
||||
eclatsPerHourCents: 200,
|
||||
stardustPerHourCents: 25,
|
||||
packPerHourPermille: 12,
|
||||
maxPacks: 2,
|
||||
difficultyPct: [100, 130, 170, 220, 300],
|
||||
tierPct: [40, 100, 150],
|
||||
fortunePerPointPct: 2,
|
||||
fortuneCapPct: 50,
|
||||
// Multiplicateur de butin des destinations bonus : 5e, puis 6e.
|
||||
bonusSlotPct: [100, 125]
|
||||
},
|
||||
destinations: {}
|
||||
});
|
||||
|
||||
export const DEFAULT_DESTINATION_SETTING = Object.freeze({ active: true, weight: 1 });
|
||||
export const MAX_DESTINATION_WEIGHT = 100;
|
||||
|
||||
const int = (path, min, max) => ({ path, kind: "int", min, max });
|
||||
const ints = (path, length, min, max) => ({ path, kind: "ints", length, min, max });
|
||||
|
||||
// Bornes de chaque réglage. `ints` : liste de longueur fixe. Les réglages par destination sont validés à part.
|
||||
export const EXPEDITION_SETTINGS_SCHEMA = Object.freeze([
|
||||
{ path: "enabled", kind: "bool" },
|
||||
int("day.destinationsPerDay", 1, 8),
|
||||
int("day.avoidRepeatDays", 0, 7),
|
||||
ints("durations.hours", 3, 1, 48),
|
||||
ints("durations.malusPct", 3, 0, 50),
|
||||
int("durations.endurancePerSlot", 1, 1000),
|
||||
int("solo.maxConcurrent", 1, 3),
|
||||
int("solo.cards", 1, 4),
|
||||
int("solo.minStars", 1, 5),
|
||||
int("solo.maxStars", 1, 5),
|
||||
int("power.rare", 1, 300),
|
||||
int("power.epic", 1, 300),
|
||||
int("power.legendary", 1, 300),
|
||||
int("power.mythic", 1, 300),
|
||||
int("power.perLevel", 0, 50),
|
||||
int("power.cap", 1, 300),
|
||||
int("roles.multiplierPct", 100, 400),
|
||||
ints("requirements.star1", 1, 1, 1000),
|
||||
ints("requirements.star2", 2, 1, 1000),
|
||||
ints("requirements.star3", 3, 1, 1000),
|
||||
ints("requirements.star4", 3, 1, 1000),
|
||||
ints("requirements.star5", 4, 1, 1000),
|
||||
int("requirements.conditionMissPct", 0, 100),
|
||||
int("danger.malusPct", 0, 90),
|
||||
int("danger.shieldMaxPct", 0, 100),
|
||||
int("danger.endurancePerSlot", 1, 1000),
|
||||
int("score.mainWeight", 1, 10),
|
||||
int("score.otherWeight", 1, 10),
|
||||
int("score.overflowPct", 0, 100),
|
||||
int("score.overflowSpanPct", 0, 300),
|
||||
int("score.capPct", 100, 300),
|
||||
int("score.successPct", 1, 300),
|
||||
int("score.triumphPct", 1, 300),
|
||||
int("loot.eclatsPerHourCents", 0, 100_000),
|
||||
int("loot.stardustPerHourCents", 0, 100_000),
|
||||
int("loot.packPerHourPermille", 0, 1000),
|
||||
int("loot.maxPacks", 0, 10),
|
||||
ints("loot.difficultyPct", 5, 0, 1000),
|
||||
ints("loot.tierPct", 3, 0, 1000),
|
||||
int("loot.fortunePerPointPct", 0, 100),
|
||||
int("loot.fortuneCapPct", 0, 500),
|
||||
ints("loot.bonusSlotPct", 2, 0, 1000)
|
||||
]);
|
||||
|
||||
const isObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
|
||||
export function readPath(source, path) {
|
||||
return path.split(".").reduce((value, key) => (isObject(value) ? value[key] : undefined), source);
|
||||
}
|
||||
|
||||
function writePath(target, path, value) {
|
||||
const keys = path.split(".");
|
||||
let node = target;
|
||||
for (const key of keys.slice(0, -1)) {
|
||||
if (!isObject(node[key])) node[key] = {};
|
||||
node = node[key];
|
||||
}
|
||||
node[keys.at(-1)] = value;
|
||||
}
|
||||
|
||||
function validField(field, value) {
|
||||
if (field.kind === "bool") return typeof value === "boolean";
|
||||
const inRange = (item) => Number.isInteger(item) && item >= field.min && item <= field.max;
|
||||
if (field.kind === "int") return inRange(value);
|
||||
return Array.isArray(value) && value.length === field.length && value.every(inRange);
|
||||
}
|
||||
|
||||
const validDestinationSetting = (value) => isObject(value) && typeof value.active === "boolean"
|
||||
&& Number.isInteger(value.weight) && value.weight >= 0 && value.weight <= MAX_DESTINATION_WEIGHT;
|
||||
|
||||
const copy = (value) => (Array.isArray(value) ? [...value] : value);
|
||||
|
||||
// Réglages complets : chaque champ stocké et valide est gardé, sinon il reprend sa valeur par défaut ; les clés inconnues disparaissent.
|
||||
export function mergeExpeditionSettings(stored, destinationIds = [], onInvalid = null) {
|
||||
const merged = {};
|
||||
for (const field of EXPEDITION_SETTINGS_SCHEMA) {
|
||||
const value = readPath(stored, field.path);
|
||||
const fallback = readPath(DEFAULT_EXPEDITION_SETTINGS, field.path);
|
||||
if (value !== undefined && !validField(field, value)) onInvalid?.(field.path);
|
||||
writePath(merged, field.path, copy(value !== undefined && validField(field, value) ? value : fallback));
|
||||
}
|
||||
merged.destinations = {};
|
||||
for (const id of destinationIds) {
|
||||
const value = isObject(stored?.destinations) ? stored.destinations[id] : undefined;
|
||||
if (value !== undefined && !validDestinationSetting(value)) onInvalid?.(`destinations.${id}`);
|
||||
merged.destinations[id] = validDestinationSetting(value) ? { active: value.active, weight: value.weight } : { ...DEFAULT_DESTINATION_SETTING };
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
// Message en français, ou null si les réglages sont valides (bornes, puis contraintes entre réglages).
|
||||
export function validateExpeditionSettings(settings, destinationIds = []) {
|
||||
if (!isObject(settings)) return "Réglages des Expéditions invalides.";
|
||||
for (const field of EXPEDITION_SETTINGS_SCHEMA) {
|
||||
if (!validField(field, readPath(settings, field.path))) {
|
||||
return field.kind === "bool"
|
||||
? `Réglage ${field.path} invalide : oui ou non.`
|
||||
: `Réglage ${field.path} invalide : ${field.kind === "ints" ? `${field.length} entiers` : "un entier"} entre ${field.min.toLocaleString("fr-FR")} et ${field.max.toLocaleString("fr-FR")}.`;
|
||||
}
|
||||
}
|
||||
if (!isObject(settings.destinations)) return "Réglages des destinations invalides.";
|
||||
for (const id of Object.keys(settings.destinations)) {
|
||||
if (!destinationIds.includes(id)) return `Destination inconnue : ${id}.`;
|
||||
if (!validDestinationSetting(settings.destinations[id])) return `Réglage de la destination ${id} invalide : active oui ou non, poids entre 0 et ${MAX_DESTINATION_WEIGHT}.`;
|
||||
}
|
||||
const { hours } = settings.durations;
|
||||
if (hours.some((value, index) => index > 0 && value <= hours[index - 1])) return "Les durées doivent être croissantes.";
|
||||
if (settings.solo.minStars > settings.solo.maxStars) return "L'étoile minimale du solo dépasse l'étoile maximale.";
|
||||
const { successPct, triumphPct, capPct } = settings.score;
|
||||
if (!(successPct < triumphPct && triumphPct <= capPct)) return "Les seuils doivent respecter Réussite < Triomphe ≤ plafond du score.";
|
||||
const { perLevel, cap, ...bases } = settings.power;
|
||||
if (Object.values(bases).some((base) => base > cap)) return "Une Puissance de base dépasse le plafond.";
|
||||
if (perLevel === 0 && Object.values(bases).some((base) => base < cap)) return "Le gain par niveau doit être positif tant qu'une Puissance de base est sous le plafond.";
|
||||
return null;
|
||||
}
|
||||
|
||||
// Différences champ par champ, pour l'historique d'administration.
|
||||
export function diffExpeditionSettings(previous, next) {
|
||||
const changes = [];
|
||||
for (const field of EXPEDITION_SETTINGS_SCHEMA) {
|
||||
const before = readPath(previous, field.path);
|
||||
const after = readPath(next, field.path);
|
||||
if (JSON.stringify(before) !== JSON.stringify(after)) changes.push({ path: field.path, previous: before, next: after });
|
||||
}
|
||||
const ids = new Set([...Object.keys(previous?.destinations || {}), ...Object.keys(next?.destinations || {})]);
|
||||
for (const id of ids) {
|
||||
for (const key of ["active", "weight"]) {
|
||||
const before = previous?.destinations?.[id]?.[key];
|
||||
const after = next?.destinations?.[id]?.[key];
|
||||
if (before !== after) changes.push({ path: `destinations.${id}.${key}`, previous: before, next: after });
|
||||
}
|
||||
}
|
||||
return changes;
|
||||
}
|
||||
107
services/cards/expedition-simulation.js
Normal file
107
services/cards/expedition-simulation.js
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
// Rôle : simule les Expéditions Sokko TCG sur toutes les équipes possibles pour vérifier l'équilibre (script et test d'équilibrage).
|
||||
// Module pur : il appelle les mêmes règles que le serveur, sans base ni hasard.
|
||||
import { cardRarity } from "./daily.js";
|
||||
import {
|
||||
cardExpeditionData, cardPower, evaluateTeam, EXPEDITION_RARITIES, expectedLoot, maxLevel, MAX_STARS, soloRoles, splitPower, TIER_IDS
|
||||
} from "./expedition-rules.js";
|
||||
|
||||
// Cartes jouables : chaque carte rare ou mieux à sa rareté, plus une mythique virtuelle pour chaque légendaire.
|
||||
export function simulationCards(catalog) {
|
||||
const cards = [];
|
||||
for (const card of catalog.cards) {
|
||||
const rarity = cardRarity(catalog, card.id);
|
||||
if (!EXPEDITION_RARITIES.includes(rarity)) continue;
|
||||
const data = cardExpeditionData(catalog, card.id);
|
||||
cards.push({ ...data, rarity });
|
||||
if (rarity === "legendary") cards.push({ ...data, rarity: "mythic" });
|
||||
}
|
||||
return cards;
|
||||
}
|
||||
|
||||
const atLevel = (card, level, settings) => {
|
||||
const power = cardPower(card.rarity, level, settings);
|
||||
return { ...card, level, power, stats: splitPower(power, card.profile) };
|
||||
};
|
||||
|
||||
const entryFor = (destination) => ({ condition: destination.conditions[0], dangers: destination.dangers.slice(0, 2) });
|
||||
|
||||
// Meilleur score d'une paire sur une destination : les deux façons de placer les cartes sur les deux rôles du solo.
|
||||
export function bestPairScore(first, second, destination, stars, durationIndex, settings) {
|
||||
const roles = soloRoles(destination, 2);
|
||||
let best = null;
|
||||
for (const [a, b] of [[first, second], [second, first]]) {
|
||||
const result = evaluateTeam({
|
||||
destination, entry: entryFor(destination), stars, durationIndex,
|
||||
slots: [{ ...a, role: roles[0] }, { ...b, role: roles[1] }]
|
||||
}, settings);
|
||||
if (!best || result.scorePct > best.scorePct) best = result;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function pairsOf(cards, filter) {
|
||||
const pairs = [];
|
||||
for (let i = 0; i < cards.length; i += 1) {
|
||||
for (let j = i + 1; j < cards.length; j += 1) {
|
||||
if (cards[i].cardId !== cards[j].cardId && filter(cards[i], cards[j])) pairs.push([cards[i], cards[j]]);
|
||||
}
|
||||
}
|
||||
return pairs;
|
||||
}
|
||||
|
||||
// Rapport complet : meilleur score de chaque carte en 2 ★, extrêmes par rareté et étoiles, butin par heure, écart rare / mythique au plafond.
|
||||
export function simulate(catalog, destinations, settings) {
|
||||
const visible = destinations.filter((destination) => !destination.hidden);
|
||||
const base = simulationCards(catalog);
|
||||
const atZero = base.map((card) => atLevel(card, 0, settings));
|
||||
const atMax = base.map((card) => atLevel(card, maxLevel(card.rarity, settings), settings));
|
||||
|
||||
// 1. Chaque carte doit atteindre Réussite en 2 ★ quelque part, avec un partenaire de même rareté, au niveau 0.
|
||||
const cardBest = atZero.map((card) => {
|
||||
let best = { scorePct: 0, destinationId: null, partnerId: null };
|
||||
for (const partner of atZero) {
|
||||
if (partner.cardId === card.cardId || partner.rarity !== card.rarity) continue;
|
||||
for (const destination of visible) {
|
||||
const result = bestPairScore(card, partner, destination, 2, 0, settings);
|
||||
if (result.scorePct > best.scorePct) best = { scorePct: result.scorePct, destinationId: destination.id, partnerId: partner.cardId };
|
||||
}
|
||||
}
|
||||
return { cardId: card.cardId, rarity: card.rarity, ...best };
|
||||
});
|
||||
|
||||
// 2. Score par rareté (paires de même rareté), étoiles et niveau : minimum, médiane et maximum sur toutes les destinations.
|
||||
const byRarity = [];
|
||||
for (const [label, cards] of [["niveau 0", atZero], ["niveau max", atMax]]) {
|
||||
for (const rarity of EXPEDITION_RARITIES) {
|
||||
const pairs = pairsOf(cards, (a, b) => a.rarity === rarity && b.rarity === rarity);
|
||||
for (let stars = 1; stars <= MAX_STARS; stars += 1) {
|
||||
const scores = [];
|
||||
for (const [a, b] of pairs) for (const destination of visible) scores.push(bestPairScore(a, b, destination, stars, 0, settings).scorePct);
|
||||
scores.sort((x, y) => x - y);
|
||||
byRarity.push({ level: label, rarity, stars, min: scores[0] ?? 0, median: scores[Math.floor(scores.length / 2)] ?? 0, max: scores.at(-1) ?? 0 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Triomphe en 4 ★ au niveau maximum : part des destinations où au moins une paire de rares au plafond triomphe.
|
||||
const maxRares = atMax.filter((card) => card.rarity === "rare");
|
||||
const triumphDestinations = visible.filter((destination) => pairsOf(maxRares, () => true)
|
||||
.some(([a, b]) => bestPairScore(a, b, destination, 4, 0, settings).tier === "triumph")).length;
|
||||
|
||||
// 4. Butin espéré par heure, pour chaque durée, étoile et palier.
|
||||
const lootPerHour = [];
|
||||
for (let stars = 1; stars <= MAX_STARS; stars += 1) {
|
||||
for (const tier of TIER_IDS) {
|
||||
const perHour = settings.durations.hours.map((hours) => expectedLoot({ hours, stars, tier, fortune: 0, slotCount: 2 }, settings).eclats / hours);
|
||||
lootPerHour.push({ stars, tier, perHour });
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
cardBest,
|
||||
byRarity,
|
||||
triumphShareAt4: visible.length ? triumphDestinations / visible.length : 0,
|
||||
lootPerHour,
|
||||
rareVsMythicAtMax: { rare: cardPower("rare", maxLevel("rare", settings), settings), mythic: cardPower("mythic", maxLevel("mythic", settings), settings) }
|
||||
};
|
||||
}
|
||||
|
|
@ -5,6 +5,8 @@ import { planRecycling, spareQuantity, validateShopSetting } from "./stardust.js
|
|||
import { FULL_ART_FORMAT, buildPublishedCatalog, createCatalogIndex, holographicFinishIds, legendaryParentEdition, MATCH_HOLO_PALETTE_ID, mythicEditionId, publicCatalog, validateRarityWeights } from "./catalog.js";
|
||||
import { computeStreak, DAILY_REPEAT_WINDOW_DAYS, dailyDayKey, dailyZoom, drawDailyPuzzle, guessHint, isDayKey, MAX_DAILY_GUESSES, nextDailyAt, shiftDayKey } from "./daily.js";
|
||||
import { calculateRecharge, pinnedRecharge, drawPack, drawShopPack, MAX_RECHARGE_INTERVAL_MS, MIN_RECHARGE_INTERVAL_MS, spendOpening } from "./game-rules.js";
|
||||
import { DEFAULT_DESTINATIONS_PATH, loadExpeditionDestinations } from "./expedition-content.js";
|
||||
import { ExpeditionService } from "./expedition-service.js";
|
||||
|
||||
const TRANSFER_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
|
|
@ -35,7 +37,7 @@ const ADMIN_HISTORY_PAGE_SIZE = 50;
|
|||
const PLAYER_HISTORY_EVENTS = Object.freeze([
|
||||
"welcome_opening", "pack_opened", "gift_pack_opened", "cards_recycled", "opening_purchased", "campaign_claimed",
|
||||
"trade_created", "trade_received", "trade_declined", "trade_joined", "trade_completed", "trade_cancelled",
|
||||
"gift_created", "gift_joined", "gift_completed", "gift_cancelled", "daily_won"
|
||||
"gift_created", "gift_joined", "gift_completed", "gift_cancelled", "daily_won", "expedition_completed", "expedition_cancelled_by_guild"
|
||||
]);
|
||||
const DEV_STARDUST = 1000;
|
||||
const DELETED_PLAYER_NAME = "Joueur supprimé";
|
||||
|
|
@ -45,7 +47,8 @@ const INACTIVE_ACCOUNT_MS = 730 * DAY_MS;
|
|||
const IDEMPOTENCY_TTL_MS = 30 * DAY_MS;
|
||||
|
||||
export class CardsService {
|
||||
constructor({ database, catalog, now = Date.now, random, devPerks = false } = {}) {
|
||||
// `destinations` : destinations des Expéditions validées ; sans elles, celles du dépôt (services/cards/content).
|
||||
constructor({ database, catalog, now = Date.now, random, devPerks = false, destinations = null } = {}) {
|
||||
// Serveur Vite local uniquement : ressources permanentes du compte de développement pour tester le jeu sans attendre.
|
||||
this.devPerks = devPerks;
|
||||
this.database = database;
|
||||
|
|
@ -55,6 +58,7 @@ export class CardsService {
|
|||
this.now = now;
|
||||
this.random = random;
|
||||
this.reloadCatalog();
|
||||
this.expeditions = new ExpeditionService(this, destinations || loadExpeditionDestinations(DEFAULT_DESTINATIONS_PATH, catalog));
|
||||
}
|
||||
|
||||
get rechargeSetting() {
|
||||
|
|
@ -452,17 +456,23 @@ export class CardsService {
|
|||
const history = this.db.prepare("SELECT event_type, entity_id, details_json, created_at FROM audit_log WHERE player_id = ? AND event_type IN (" + PLAYER_HISTORY_EVENTS.map(() => "?").join(", ") + ") ORDER BY created_at DESC LIMIT 100").all(playerId, ...PLAYER_HISTORY_EVENTS)
|
||||
.map((row) => ({ type: row.event_type, entityId: row.entity_id, details: JSON.parse(row.details_json), createdAt: row.created_at }));
|
||||
const transferRows = this.db.prepare("SELECT * FROM transfers WHERE initiator_id = ? OR recipient_id = ? ORDER BY created_at DESC LIMIT 50").all(playerId, playerId);
|
||||
const giftPacks = this.db.prepare(`SELECT g.id, g.collection_id, g.options_json, g.created_at, c.name AS campaign_name
|
||||
FROM gift_packs g JOIN campaigns c ON c.id = g.campaign_id WHERE g.player_id = ? AND g.opening_id IS NULL ORDER BY g.created_at`).all(playerId)
|
||||
.map((row) => ({ id: row.id, collectionId: row.collection_id, campaignName: row.campaign_name, receivedAt: row.created_at, options: JSON.parse(row.options_json) }));
|
||||
// Un paquet offert vient d'une campagne (son nom) ou d'une expédition (le nom de sa destination).
|
||||
const giftPacks = this.db.prepare(`SELECT g.id, g.source, g.collection_id, g.options_json, g.created_at, c.name AS campaign_name, e.setup_json
|
||||
FROM gift_packs g LEFT JOIN campaigns c ON c.id = g.campaign_id LEFT JOIN expeditions e ON e.id = g.expedition_id
|
||||
WHERE g.player_id = ? AND g.opening_id IS NULL ORDER BY g.created_at`).all(playerId)
|
||||
.map((row) => ({
|
||||
id: row.id, source: row.source, collectionId: row.collection_id, receivedAt: row.created_at, options: JSON.parse(row.options_json),
|
||||
campaignName: row.campaign_name ?? null, sourceName: row.source === "expedition" ? JSON.parse(row.setup_json).destination.name : row.campaign_name
|
||||
}));
|
||||
const openingsCount = this.db.prepare("SELECT COUNT(*) AS count FROM openings WHERE player_id = ?").get(playerId).count;
|
||||
const shop = this.shopSetting;
|
||||
const recycling = this.recyclingPlan(owned);
|
||||
return {
|
||||
player: publicPlayer(player), recharge, collection, favorites,
|
||||
wallet: { stardust: player.stardust, purchasedOpenings: player.purchased_openings },
|
||||
wallet: { stardust: player.stardust, purchasedOpenings: player.purchased_openings, eclats: player.eclats },
|
||||
shop: { stardustValues: shop.stardustValues, openingPrice: shop.openingPrice, shopPackPrice: shop.shopPackPrice, shopPackShare: shop.shopPackShare, dailyReward: shop.dailyReward },
|
||||
daily: this.dailySummary(playerId),
|
||||
expeditions: this.expeditions.summary(playerId),
|
||||
recycling: { count: recycling.count, stardust: recycling.stardust },
|
||||
pendingOpening: pending ? this.openingById(pending.id, playerId) : null,
|
||||
rarestPull: this.rarestPull(playerId), stats: { openingsCount },
|
||||
|
|
@ -534,6 +544,8 @@ export class CardsService {
|
|||
rechargeSetting: this.rechargeSetting,
|
||||
shopSetting: this.shopSetting,
|
||||
daily: this.dailyAdminSummary(),
|
||||
expeditionSettings: this.expeditions.adminSettings(),
|
||||
expeditionsToday: this.expeditions.adminSummary(),
|
||||
campaigns: this.campaignSummaries(),
|
||||
editionCampaigns: this.editionCampaignCounts(),
|
||||
// Variations possédées ou citées par une ouverture ou un transfert passés : elles ne peuvent qu'être retirées.
|
||||
|
|
@ -655,7 +667,7 @@ export class CardsService {
|
|||
const editionIds = drawPack(this.catalog, gift.collection_id, this.random, { weights: options.rarityWeights, guarantee: options.guarantee, requireActive: false });
|
||||
const openingId = this.insertOpening(playerId, gift.collection_id, editionIds);
|
||||
this.db.prepare("UPDATE gift_packs SET opening_id = ?, opened_at = ? WHERE id = ?").run(openingId, this.now(), gift.id);
|
||||
this.audit(playerId, "gift_pack_opened", openingId, { collectionId: gift.collection_id, campaignId: gift.campaign_id, cards: editionIds });
|
||||
this.audit(playerId, "gift_pack_opened", openingId, { collectionId: gift.collection_id, campaignId: gift.campaign_id, ...(gift.expedition_id ? { expeditionId: gift.expedition_id } : {}), cards: editionIds });
|
||||
return openingId;
|
||||
});
|
||||
}
|
||||
|
|
@ -860,9 +872,10 @@ export class CardsService {
|
|||
: { sent: transfer.offered_edition_id, received: transfer.requested_edition_id });
|
||||
}
|
||||
this.db.prepare("UPDATE openings SET status = 'completed', completed_at = ? WHERE player_id = ? AND status = 'pending'").run(this.now(), playerId);
|
||||
this.expeditions.forgetPlayer(playerId);
|
||||
for (const table of ["sessions", "collection_cards", "favorites", "idempotency", "daily_attempts"]) this.db.prepare(`DELETE FROM ${table} WHERE player_id = ?`).run(playerId);
|
||||
this.db.prepare("DELETE FROM gift_packs WHERE player_id = ? AND opening_id IS NULL").run(playerId);
|
||||
this.db.prepare(`UPDATE players SET discord_id = ?, display_name = ?, avatar_url = '', is_admin = 0, openings_balance = 0, recharge_anchor = NULL, stardust = 0, purchased_openings = 0, deleted_at = ? WHERE id = ?`)
|
||||
this.db.prepare(`UPDATE players SET discord_id = ?, display_name = ?, avatar_url = '', is_admin = 0, openings_balance = 0, recharge_anchor = NULL, stardust = 0, purchased_openings = 0, eclats = 0, deleted_at = ? WHERE id = ?`)
|
||||
.run(`deleted:${randomUUID()}`, DELETED_PLAYER_NAME, this.now(), playerId);
|
||||
this.audit(playerId, "account_deleted", playerId, auditDetails);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue