diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index 1258303..1cb0fe1 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -342,3 +342,6 @@ {"id":"int-fc8f33bf9d1c8430b05a605f18235998","kind":"field_change","created_at":"2026-11-13T14:14:53.924973488Z","actor":"Shinuwa","issue_id":"sokko-g-v745","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Closed"}} {"id":"int-79c8d43e37370ddf8840cacd2bc4a923","kind":"field_change","created_at":"2026-11-14T09:45:12.274352406Z","actor":"Shinuwa","issue_id":"sokko-g-tabc","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}} {"id":"int-e9b4ee305fdf02151292a856d60926dc","kind":"field_change","created_at":"2026-11-14T15:21:07.54864269Z","actor":"Shinuwa","issue_id":"sokko-g-03ij","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}} +{"id":"int-b85db20f07bf7f3813ce379b1a4cf2b5","kind":"field_change","created_at":"2026-11-15T12:45:03.198722539Z","actor":"Shinuwa","issue_id":"sokko-g-v3u4.1","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Doc de conception corrigé (étape 0 du plan)."}} +{"id":"int-2eb4267321abcd9d03371b62fdd602ef","kind":"field_change","created_at":"2026-11-15T12:58:18.78522507Z","actor":"Shinuwa","issue_id":"sokko-g-v3u4.2","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Étiquettes et profils dans le catalogue + validation, 12 destinations côté serveur + validation, réglages (schéma, défauts, fusion, validation, diff), règles pures, simulateur et test d'équilibrage, docs agent et skill new-card. npm test : 300/300."}} +{"id":"int-13028497227d5b47c5cac5cc0d43849f","kind":"field_change","created_at":"2026-11-15T13:19:13.339585179Z","actor":"Shinuwa","issue_id":"sokko-g-v3u4.3","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Expéditions solo livrées : migration 8, service + API, panneau joueur, tuile de Guilde, réglages et suivi en administration, historique, tests Node (309) et e2e (13/13), docs."}} diff --git a/.claude/skills/new-card/SKILL.md b/.claude/skills/new-card/SKILL.md new file mode 100644 index 0000000..93376d8 --- /dev/null +++ b/.claude/skills/new-card/SKILL.md @@ -0,0 +1,12 @@ +--- +name: new-card +description: Ajouter ou modifier une carte Sokko TCG (catalog.json) en la rendant jouable dans les Expéditions — étiquettes, profil, vérification d'équilibre. À utiliser dès qu'une carte ou une collection est créée ou que sa description change. +--- + +Suivre la section « Ajouter une carte aux Expéditions » de `docs/collections/archipel-lore.md`, qui fait autorité : + +1. Poser les étiquettes de la carte (`cards[].expedition.tags`) à partir de sa description et du lore, en réutilisant le vocabulaire `expeditionTags` du catalogue. +2. Ne donner un profil propre (`cards[].expedition.profile`) qu'aux cartes au caractère marqué ; sinon la carte prend le profil de sa collection. +3. Lancer `node scripts/simulate-expeditions.mjs`, puis `npm run test:cards`. + +Pour une nouvelle collection : lui donner aussi `collections[].expedition.profile`. diff --git a/DESIGN_SYSTEM.md b/DESIGN_SYSTEM.md index b6b7ba5..4623b6e 100644 --- a/DESIGN_SYSTEM.md +++ b/DESIGN_SYSTEM.md @@ -1093,7 +1093,7 @@ car les attributs NDS sont chargés après `_nebula-cards.scss`. Le tableau de b sections adressables (`/#/cards/admin/
`), dans une navigation par liens avec `aria-current="page"`, sans intitulés de groupe : Vue d'ensemble (`overview`), Collections (`collections`), Codes cadeaux (`codes`), Boutique -(`shop`) et Guilde (`guild`, réglages des quêtes : partie du jour et récompense de la Carte du jour), puis, séparé par un filet, l'Atelier visuel (`visual-lab`), bac à sable +(`shop`) et Guilde (`guild`, réglages des quêtes : partie du jour et récompense de la Carte du jour, réglages et suivi des Expéditions), puis, séparé par un filet, l'Atelier visuel (`visual-lab`), bac à sable où rien n'est enregistré. Les anciennes adresses redirigent : `players` vers la vue d'ensemble, `cards`, `catalog` et `packs` vers Collections, `distributions` vers Codes cadeaux, `mythic-styles` et `opening-effects` vers l'Atelier visuel. Quand le tableau de bord dispose d'au @@ -1476,3 +1476,16 @@ par indice. Sous 720 px de conteneur, les deux colonnes s'empilent. La fin de pa le formulaire par un `nds-panel` : titre, réponse et description, badges (poussière gagnée, possession, série), bouton primaire « Copier le résultat » et compte à rebours, avec la carte en `md` à droite. + +Les Expéditions (`expeditions`, sans entrée propre : le menu désigne la Guilde) ont leur tuile dans la +Guilde tant qu'elles sont ouvertes ou qu'une expédition du joueur n'est pas terminée. Leur page +(`_nebula-expeditions.scss`) reprend l'en-tête de la Carte du jour (solde d'Éclats en badge `gold`, +retour secondaire vers la Guilde), puis les expéditions du joueur en `nds-card` (couverture carrée de +la destination, palier et butin en badges, équipe en cartes `sm`, bouton primaire « Récupérer le +butin »), puis quatre étapes en `nds-panel` : destinations du jour (boutons à `aria-pressed`, contour +or quand choisis), difficulté et durée (`nds-toolbar` de boutons `sm`) avec les exigences, équipe +(une place par rôle, puis les cartes jouables en `sm` triées pour la place active) et aperçu (palier, +exigences atteintes en `success`, condition et dangers en `nds-inline-notice`, butin attendu). +En administration, la section Guilde ajoute sous la Carte du jour un panneau par groupe de réglages +des Expéditions (champs en grille, listes de valeurs côte à côte, `ApplyActions`), les destinations +(proposée ou retirée, poids) et le suivi du jour avec l'annulation d'une expédition en cours. diff --git a/README.md b/README.md index 895b2c8..4601188 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,10 @@ L'interface cible les fenêtres d'ordinateur en plein écran ou en demi-écran. - Guilde des Veilleurs de Sokko TCG, qui confie des quêtes, dont la Carte du jour : un défi quotidien commun à tous les joueurs, qui consiste à retrouver une illustration zoomée en 6 essais, avec des indices de collection et de rareté, une récompense en poussière d'étoiles et un résultat à partager. +- Expéditions de Sokko TCG, seconde quête de la Guilde : des cartes rares ou mieux partent en + solo vers une destination du jour (difficulté, durée, rôles, dangers) et rapportent des Éclats + d'étoile, de la poussière et parfois un paquet. Toutes les valeurs se règlent dans + l'administration ; `node scripts/simulate-expeditions.mjs` affiche le rapport d'équilibrage. ## Démarrage diff --git a/docs/AGENTS.md b/docs/AGENTS.md index 67ee97b..e8a4a89 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -11,6 +11,10 @@ Cette zone contient les références projet. `TEST_STRATEGY.md` définit les validations selon le risque et distingue tests Node, E2E Vite, E2E du build et contrôles HTTP du serveur livré. +`collections/archipel-lore.md` fait autorité pour le lore des cartes Sokko TCG +et, dans sa section « Ajouter une carte aux Expéditions », pour les étiquettes +et profils qu'une nouvelle carte doit porter. + `P06_USAGE_STUDY.md` consigne l'arbitrage conservateur des prochains usages et les conditions nécessaires pour le réexaminer. diff --git a/docs/STORAGE_SCHEMA.md b/docs/STORAGE_SCHEMA.md index d4d791d..efd3605 100644 --- a/docs/STORAGE_SCHEMA.md +++ b/docs/STORAGE_SCHEMA.md @@ -19,9 +19,9 @@ Collections, ouvertures et transferts : - `players.deleted_at` (migration 5) : date de suppression du compte. `DELETE /api/cards/account` efface sessions, collection, favoris, clés - d'idempotence, parties de la Carte du jour et paquets offerts non ouverts, annule les échanges ouverts, clôt + d'idempotence, parties de la Carte du jour et paquets offerts non ouverts, annule les échanges ouverts et les expéditions en cours, clôt une ouverture en attente et anonymise la ligne (`discord_id = deleted:`, - nom « Joueur supprimé », avatar et soldes remis à zéro). Elle reste car ouvertures, + nom « Joueur supprimé », avatar et soldes, Éclats compris, remis à zéro). Elle reste car ouvertures, transferts, réclamations de codes et journaux la référencent. Le compte disparaît des listes de joueurs ; une reconnexion Discord crée un compte neuf. - `players.last_login_at` (migration 6) : dernière connexion Discord. @@ -111,6 +111,52 @@ Carte du jour (migration 7, règles pures dans `services/cards/daily.js`) : poussière) dans l'historique du joueur. Chaque essai renvoie aussi l'état complet, dont le résumé `daily` (statut, essais, série) qui alimente le bandeau et la page de la Guilde des Veilleurs. +Expéditions (migration 8, règles pures dans `services/cards/expedition-rules.js`, service dans +`services/cards/expedition-service.js`, réglages dans `services/cards/expedition-settings.js`) : + +- `players.eclats` : Éclats d'étoile du joueur (entier ≥ 0), monnaie des Expéditions, distincte de la poussière. +- `expedition_settings(id = 1, settings_json, updated_at, updated_by)` : tous les réglages des + Expéditions dans un JSON validé champ par champ (`EXPEDITION_SETTINGS_SCHEMA`, seule source des + bornes). À la lecture, un champ absent ou invalide reprend sa valeur par défaut + (`DEFAULT_EXPEDITION_SETTINGS`) : une valeur ajoutée plus tard ne demande pas de migration. Les + Expéditions sont fermées (`enabled: false`) jusqu'à ce qu'un administrateur les ouvre. +- `expedition_days(day, draw_json, created_at)` : destinations du jour de Paris, tirées au premier + appel (identifiant, indice de la condition, indices de deux dangers). Les exigences chiffrées sont + calculées à la lecture avec les réglages en vigueur, puis figées au départ. +- `expeditions(id, mode, day, destination_id, difficulty, duration_ms, creator_id, status, setup_json, + result_json, created_at, departs_at, returns_at, completed_at)` : `mode` `solo` ou `group`, + `status` `forming`, `running`, `completed` ou `cancelled` (« revenue » se déduit de `returns_at`). + `setup_json` fige la destination, la condition, les étoiles, la durée et les rôles ; `result_json` + (score, palier, exigences, dangers) est calculé au départ et n'est montré qu'au retour. +- `expedition_members(expedition_id, player_id, reward_json, joined_at, claimed_at)` : butin tiré au + départ (`{ eclats, stardust, packs: [collectionId…] }`), crédité une seule fois au retour. +- `expedition_slots(expedition_id, position, role, player_id, edition_id, card_id, level, stats_json)` : + une place par carte ; `player_id` nul pour une place tenue par le Veilleur de la Guilde. Une édition + est occupée tant qu'elle est dans une expédition `running` dont son propriétaire n'a pas récupéré le + butin. L'exemplaire gardé ne quitte jamais la collection : échanges et recyclage ne changent pas. +- `gift_packs.source` (`campaign` ou `expedition`) et `gift_packs.expedition_id` : la table est + reconstruite par la migration 8 ; `campaign_id` devient facultatif. Un paquet rapporté s'ouvre + comme un paquet offert ; `getState().giftPacks[]` donne `source` et `sourceName`. +- `GET /api/cards/expeditions` : réglages utiles au joueur, destinations du jour (rôles du solo et, + pour chaque étoile, exigences, condition et dangers), cartes jouables (rare ou mieux, Puissance, + stats, occupation) et expéditions du joueur. Fermées : aucune destination n'est tirée, mais le + butin des expéditions revenues se récupère. +- `POST /api/cards/expeditions/preview` : aperçu exact d'une équipe, sans écriture. +- `POST /api/cards/expeditions` (`Idempotency-Key`, `{ day, destinationId, difficulty, durationHours, + slots: [editionId…] }`) : `EXPEDITIONS_CLOSED`, `EXPEDITION_DAY_EXPIRED`, `EXPEDITION_INVALID`, + `EXPEDITION_CARD_INVALID`, `CARD_NOT_OWNED`, `EXPEDITION_CARD_BUSY`, `EXPEDITION_LIMIT`. +- `POST /api/cards/expeditions/:id/claim` : idempotent ; `EXPEDITION_NOT_FOUND`, + `EXPEDITION_NOT_RETURNED`. Inscrit `expedition_completed` dans l'historique du joueur. +- `PUT /api/cards/admin/expeditions/settings` (`{ settings }`, objet complet) : + `EXPEDITION_SETTINGS_INVALID`, `EXPEDITION_SETTINGS_UNCHANGED` ; l'historique d'administration + garde `expedition_settings_updated` avec la liste des changements (`{ path, previous, next }`). +- `POST /api/cards/admin/expeditions/:id/cancel` : libère les cartes sans butin ; `expedition_cancelled` + côté administration, `expedition_cancelled_by_guild` dans l'historique du joueur. +- `getState().expeditions` : résumé pour la tuile de la Guilde et la fiche de carte (ouverture, en + route, revenues, prochain retour, lancée aujourd'hui, cartes jouables, éditions occupées) ; + `getState().wallet.eclats`. Le tableau de bord d'administration ajoute `expeditionSettings` + (réglages, valeurs par défaut, schéma, destinations) et `expeditionsToday`. + Distributions par codes : - `campaigns(id, name, code, reward_json, max_claims, created_by, created_at, expires_at, revoked_at)` : @@ -165,6 +211,13 @@ paquets (`collections[].active`), ni taux de tirage (`dropTables`, `loadCardsCatalog` → `prepareVersionedCatalog` refuse un fichier qui en contient (`assertVersionedCatalogScope`). +Il porte aussi les données des Expéditions, validées au chargement : `expeditionTags` +(vocabulaire fermé d'étiquettes `famille:nom` et leurs libellés), `collections[].expedition.profile` +(part de la Puissance donnée à chaque stat, somme 100, obligatoire) et `cards[].expedition` +(`tags` obligatoires, 1 à 8 ; `profile` facultatif). Les destinations des Expéditions vivent +côté serveur, dans `services/cards/content/expedition-destinations.json` +(`validateExpeditionDestinations`) : elles ne sont jamais publiées en fichier statique. + Les finitions sont générées (`withGeneratedFinishes`) : `standard`, puis une finition `-` par combinaison effet holographique × palette. Une finition ne porte pas de particules : les particules n'existent que pendant diff --git a/docs/collections/archipel-lore.md b/docs/collections/archipel-lore.md index 6bd66c8..5e40048 100644 --- a/docs/collections/archipel-lore.md +++ b/docs/collections/archipel-lore.md @@ -74,3 +74,19 @@ Les prompts d'illustration (style crayon et pastel, premier plan en papier déco - **Genèse Astrale** : collection événement sur le plaisir de collectionner. C'est un à-côté : les Primordiaux (Dragon, Kitsune, Pie, Capybara, Panda) y ouvrent et échangent des paquets. Elle ne suit pas l'histoire de l'archipel, mais respecte les noms, le genre et le caractère des personnages (Lune Écarlate, Kitsune au masculin, Dragon toujours nommé en entier). On y dit « paquet », comme sur le reste du site. - **Poussières d'étoiles** : collection de la boutique. Elle n'est pas rattachée au lore de l'archipel. + +## Ajouter une carte aux Expéditions + +Chaque carte du catalogue (`website/public/data/cards/catalog.json`) doit être jouable dans les Expéditions dès sa création. Le chargement du catalogue échoue, et donc `npm run test:cards`, si une carte n'a pas ses données d'expédition. + +1. **Étiquettes** (`cards[].expedition.tags`, 1 à 8, obligatoires même pour une commune) : choisies dans `expeditionTags`, en haut du catalogue. Une étiquette suit la forme `famille:nom`, avec quatre familles : + - `personnage:` pour l'animal ou le Primordial montré (un même animal garde la même étiquette d'une collection à l'autre : c'est ce qui permettra les Échos) ; + - `lieu:` pour un lieu de l'archipel (Lune Écarlate, vide, îles de glace, îles-jeux…) ; + - `theme:` pour ce dont parle la description (Veilleurs, voyage, hiver, fête, rêves…) ; + - `objet:` pour une commune qui montre un objet (lunette, boussole, lanterne, cadeau…). + + On part de la description de la carte et de ce document. Une étiquette nouvelle s'ajoute à `expeditionTags` (libellé de 40 caractères au plus) ; une étiquette que plus aucune carte n'utilise doit en être retirée (test « every catalog card carries expedition tags »). +2. **Profil** (`cards[].expedition.profile`, facultatif) : la part de la Puissance donnée à chaque stat, en entiers dont la somme vaut 100 : `{ "bravoure", "endurance", "fortune", "orientation" }`. Sans profil, la carte prend celui de sa collection (`collections[].expedition.profile`, obligatoire pour toute collection). On ne donne un profil propre qu'aux cartes au caractère marqué (un guide en Orientation, un gardien en Endurance…), sans dépasser 50 sur une stat. +3. **Vérifier l'équilibre** : `node scripts/simulate-expeditions.mjs`, puis `npm run test:cards`. Le test d'équilibrage (`tests/nebula-cards-expedition-balance.test.mjs`) échoue si une carte rare ou mieux ne peut atteindre « Réussite » en 2 ★ nulle part. + +Les destinations (`services/cards/content/expedition-destinations.json`, côté serveur pour garder secrètes les destinations cachées) citent des étiquettes dans leurs conditions et leurs dangers : chacune doit rester portée par au moins 3 cartes rare ou mieux, sinon le chargement échoue. Une mythique reprend les étiquettes et le profil de sa carte légendaire. diff --git a/e2e/nebula-cards.spec.js b/e2e/nebula-cards.spec.js index a811e76..09343cf 100644 --- a/e2e/nebula-cards.spec.js +++ b/e2e/nebula-cards.spec.js @@ -1,5 +1,5 @@ // Rôle : valide l'ouverture, la reprise, l'album et l'administration de Sokko TCG. -import { readFile } from "node:fs/promises"; +import { readFile, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { expect, test } from "@playwright/test"; @@ -1822,3 +1822,79 @@ test("a player finds the daily card with hints and copies the result", async ({ await expect(quest.locator(".nebula-quest-media .nds-badge")).toHaveText("Série : 1 jour"); await expect(quest.getByRole("link", { name: "Voir le résultat", exact: true })).toBeVisible(); }); + +// Dernier parcours : il ouvre les Expéditions et décale l'horloge du serveur, deux réglages globaux qu'il remet en place à la fin. +test("an administrator opens expeditions and a player sends a team, then claims its loot", async ({ browser, page }) => { + const clockFile = join(tmpdir(), "sokkog-cards-e2e-clock.json"); + const setServerClock = (offsetMs) => writeFile(clockFile, JSON.stringify({ offsetMs })); + await setServerClock(0); + await page.goto("/#/cards"); + await page.getByRole("button", { name: "Version développement", exact: true }).click(); + await page.goto("/#/cards/admin/guild"); + const general = page.getByRole("region", { name: "Général", exact: true }); + const openToggle = general.getByRole("button", { name: "Expéditions ouvertes aux joueurs", exact: true }); + await expect(openToggle).toHaveAttribute("aria-pressed", "false"); + await openToggle.click(); + await general.getByRole("button", { name: "Appliquer", exact: true }).click(); + await page.getByRole("dialog").getByRole("button", { name: "Appliquer", exact: true }).click(); + await expect(general.getByRole("button", { name: "Expéditions ouvertes aux joueurs", exact: true })).toHaveAttribute("aria-pressed", "true"); + await expect(page.getByRole("region", { name: "Destinations", exact: true }).getByRole("listitem")).toHaveCount(12); + + // Le partenaire possède deux légendaires distinctes : de quoi partir en solo. + const { token } = JSON.parse(await readFile(join(tmpdir(), "sokkog-cards-e2e-partner.json"), "utf8")); + const partnerContext = await browser.newContext({ baseURL: "http://127.0.0.1:4180", viewport: { width: 1280, height: 900 } }); + await partnerContext.addCookies([{ name: "__Host-sokkog_cards_session", value: token, domain: "127.0.0.1", path: "/", secure: true, httpOnly: true, sameSite: "Lax" }]); + const partner = await partnerContext.newPage(); + await partner.goto("/#/cards/guild"); + const quest = partner.getByRole("article", { name: "Expéditions" }); + await expect(quest).toContainText("De nouvelles destinations vous attendent."); + await quest.getByRole("link", { name: "Préparer", exact: true }).click(); + await expect(partner).toHaveURL(/#\/cards\/expeditions$/); + await expect(partner.getByRole("navigation", { name: "Sections de Sokko TCG" }).getByRole("link", { name: /^Guilde/ })).toHaveAttribute("aria-current", "page"); + + const destinations = partner.getByRole("region", { name: "1. Destination du jour" }).getByRole("button"); + await expect(destinations).toHaveCount(4); + await expect(destinations.first()).toHaveAttribute("aria-pressed", "true"); + const settings = partner.getByRole("region", { name: "2. Difficulté et durée" }); + await settings.getByRole("button", { name: "★", exact: true }).click(); + await settings.getByRole("button", { name: "2 h", exact: true }).click(); + const team = partner.getByRole("region", { name: "3. Équipe" }); + await team.getByRole("button", { name: /^Placer Loup des Aurores en / }).click(); + await team.getByRole("button", { name: /^Placer Dragon du Néant Étoilé en / }).first().click(); + const preview = partner.getByRole("region", { name: "4. Aperçu" }); + await expect(preview).toContainText(/Butin attendu : environ [\d,]+ Éclats/); + await expect(preview.locator(".nebula-expedition-preview .nds-badge").first()).toHaveText(/^(Retour difficile|Réussite|Triomphe)$/); + await preview.getByRole("button", { name: "Partir en expédition", exact: true }).click(); + await expect(partner.getByRole("status").filter({ hasText: "Expédition lancée !" })).toBeVisible(); + const report = partner.locator(".nebula-expedition-report").first(); + await expect(report).toContainText(/En route, retour dans (1 h|2 h)/); + await expect(partner.getByText("Récupérez le butin de votre expédition avant d’en lancer une autre.")).toBeVisible(); + + // En demi-écran, la page reste sans défilement horizontal. + await partner.setViewportSize({ width: 768, height: 900 }); + expect(await partner.locator(".nebula-expeditions").evaluate((element) => element.scrollWidth - element.clientWidth)).toBe(0); + await partner.setViewportSize({ width: 1280, height: 900 }); + + // Trois heures plus tard pour le serveur : l'expédition est revenue, son butin se récupère une fois. + await setServerClock(3 * 3_600_000); + await partner.reload(); + await expect(report).toContainText("De retour ! Le butin vous attend."); + await report.getByRole("button", { name: "Récupérer le butin", exact: true }).click(); + await expect(partner.getByRole("status").filter({ hasText: "Butin récupéré !" })).toBeVisible(); + await expect(report).toContainText("Butin récupéré."); + await expect(report.locator(".nebula-expedition-rewards .nds-badge").filter({ hasText: /^\+[\d\s]+ Éclats$/ })).toBeVisible(); + await expect(partner.locator(".nebula-expeditions .nds-section-heading .nds-badge")).not.toHaveText("0 Éclats d’étoile"); + await partner.getByRole("navigation", { name: "Sections de Sokko TCG" }).getByRole("link", { name: "Historique", exact: true }).click(); + await expect(partner.locator(".nebula-history-list li").filter({ hasText: "Expédition terminée" })).toContainText("★ · 2 h"); + await partnerContext.close(); + + // L'historique d'administration détaille le réglage ; on referme les Expéditions et on remet l'horloge. + await page.goto("/#/cards/admin/history"); + await expect(page.locator(".nds-list-row").filter({ hasText: "Expéditions modifiées" }).first()).toContainText("Expéditions ouvertes aux joueurs : non → oui"); + await page.goto("/#/cards/admin/guild"); + await general.getByRole("button", { name: "Expéditions ouvertes aux joueurs", exact: true }).click(); + await general.getByRole("button", { name: "Appliquer", exact: true }).click(); + await page.getByRole("dialog").getByRole("button", { name: "Appliquer", exact: true }).click(); + await expect(general.getByRole("button", { name: "Expéditions ouvertes aux joueurs", exact: true })).toHaveAttribute("aria-pressed", "false"); + await setServerClock(0); +}); diff --git a/package.json b/package.json index ba24eac..6ea2a0d 100644 --- a/package.json +++ b/package.json @@ -15,12 +15,12 @@ "preview": "vite preview", "lists:index": "node scripts/generate-list-indexes.mjs", "lint": "eslint .", - "lint:cards": "eslint server.mjs vite.config.js services/http.js playwright.cards.config.js scripts/backup-nebula-cards.mjs scripts/start-cards-e2e-server.mjs services/cards tests/nebula-cards.test.mjs tests/nebula-cards-api.test.mjs tests/nebula-cards-daily.test.mjs tests/server-robustness.test.mjs e2e/nebula-cards.spec.js e2e/style-layouts.spec.js website/src/features/cards website/src/components/Shell.jsx website/src/main.jsx website/src/router/RouteContent.jsx", + "lint:cards": "eslint server.mjs vite.config.js services/http.js playwright.cards.config.js scripts/backup-nebula-cards.mjs scripts/start-cards-e2e-server.mjs scripts/simulate-expeditions.mjs services/cards tests/nebula-cards.test.mjs tests/nebula-cards-api.test.mjs tests/nebula-cards-daily.test.mjs tests/nebula-cards-expeditions.test.mjs tests/nebula-cards-expedition-balance.test.mjs tests/nebula-cards-expedition-service.test.mjs tests/server-robustness.test.mjs e2e/nebula-cards.spec.js e2e/style-layouts.spec.js website/src/features/cards website/src/components/Shell.jsx website/src/main.jsx website/src/router/RouteContent.jsx", "check": "node --check server.mjs && node --check vite.config.js && npm run lint && npm run lists:index && npm test && npm run build", "check:cards": "node --check server.mjs && node --check vite.config.js && npm run lint:cards && npm run test:cards && npm run test:e2e:cards", "check:full": "npm run check && E2E_PORT=4181 npm run test:e2e && npm run test:e2e:production && npm run test:e2e:cards", "test": "node --test", - "test:cards": "node --test tests/nebula-cards.test.mjs tests/nebula-cards-api.test.mjs tests/nebula-cards-daily.test.mjs tests/server-robustness.test.mjs && node --test --test-name-pattern=\"site content json is complete\" tests/data-validation.test.mjs", + "test:cards": "node --test tests/nebula-cards.test.mjs tests/nebula-cards-api.test.mjs tests/nebula-cards-daily.test.mjs tests/nebula-cards-expeditions.test.mjs tests/nebula-cards-expedition-balance.test.mjs tests/nebula-cards-expedition-service.test.mjs tests/server-robustness.test.mjs && node --test --test-name-pattern=\"site content json is complete\" tests/data-validation.test.mjs", "test:e2e": "playwright test", "test:e2e:production": "npm run build && playwright test --config playwright.production.config.js", "test:e2e:cards": "playwright test --config playwright.cards.config.js", diff --git a/scripts/simulate-expeditions.mjs b/scripts/simulate-expeditions.mjs new file mode 100644 index 0000000..be222a1 --- /dev/null +++ b/scripts/simulate-expeditions.mjs @@ -0,0 +1,27 @@ +// Rôle : affiche le rapport d'équilibrage des Expéditions Sokko TCG (réglages par défaut, catalogue et destinations du dépôt). +// Usage : node scripts/simulate-expeditions.mjs. À relancer après l'ajout de cartes, d'étiquettes, de destinations ou un changement de réglages. +import { fileURLToPath } from "node:url"; +import { loadCardsCatalog } from "../services/cards/catalog.js"; +import { loadExpeditionDestinations } from "../services/cards/expedition-content.js"; +import { DEFAULT_EXPEDITION_SETTINGS, mergeExpeditionSettings } from "../services/cards/expedition-settings.js"; +import { simulate } from "../services/cards/expedition-simulation.js"; + +const root = fileURLToPath(new URL("..", import.meta.url)); +const catalog = loadCardsCatalog(`${root}website/public/data/cards/catalog.json`); +const destinations = loadExpeditionDestinations(`${root}services/cards/content/expedition-destinations.json`, catalog); +const settings = mergeExpeditionSettings(DEFAULT_EXPEDITION_SETTINGS, destinations.map((destination) => destination.id)); +const report = simulate(catalog, destinations, settings); +const pct = (value) => `${value.toFixed(0).padStart(3)} %`; + +console.log(`Paliers : Réussite à ${settings.score.successPct} %, Triomphe à ${settings.score.triumphPct} %.\n`); +console.log("Score des paires de même rareté (minimum / médiane / maximum sur les destinations, 2 h) :"); +for (const row of report.byRarity) { + console.log(` ${row.level.padEnd(10)} ${row.rarity.padEnd(9)} ${row.stars} ★ ${pct(row.min)} / ${pct(row.median)} / ${pct(row.max)}`); +} +const weakest = [...report.cardBest].sort((a, b) => a.scorePct - b.scorePct).slice(0, 10); +console.log("\nCartes au meilleur score le plus bas en 2 ★ (niveau 0, partenaire de même rareté) :"); +for (const card of weakest) console.log(` ${pct(card.scorePct)} ${card.cardId} (${card.rarity}) à ${card.destinationId} avec ${card.partnerId}`); +console.log(`\nDestinations où une paire de rares au plafond triomphe en 4 ★ : ${(report.triumphShareAt4 * 100).toFixed(0)} %`); +console.log(`Puissance au plafond : rare ${report.rareVsMythicAtMax.rare}, mythique ${report.rareVsMythicAtMax.mythic}`); +console.log("\nÉclats espérés par heure (durées " + settings.durations.hours.join(" / ") + " h) :"); +for (const row of report.lootPerHour) console.log(` ${row.stars} ★ ${row.tier.padEnd(9)} ${row.perHour.map((value) => value.toFixed(2)).join(" / ")}`); diff --git a/scripts/start-cards-e2e-server.mjs b/scripts/start-cards-e2e-server.mjs index 20e32e8..fe27eea 100644 --- a/scripts/start-cards-e2e-server.mjs +++ b/scripts/start-cards-e2e-server.mjs @@ -1,5 +1,5 @@ // Rôle : démarre le build avec une base Sokko TCG temporaire pour les parcours Playwright. -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -34,11 +34,30 @@ insertVariation.run("mythic-card-pull-spectral-prism-solar", "mythic-card-pull", seedService.addCard(partner.id, "starvoid-dragon-spectral-prism-aurora"); seedDatabase.close(); +// Horloge du serveur décalable par les parcours (retour d'une expédition sans attendre des heures) : le décalage, en millisecondes, +// est lu dans ce fichier, relu au plus toutes les 200 ms. Il repart de zéro à chaque démarrage. +const clockFile = join(tmpdir(), "sokkog-cards-e2e-clock.json"); +writeFileSync(clockFile, JSON.stringify({ offsetMs: 0 })); +let clockOffset = 0; +let clockReadAt = 0; +function now() { + const real = Date.now(); + if (real - clockReadAt > 200) { + clockReadAt = real; + try { + clockOffset = Number(JSON.parse(readFileSync(clockFile, "utf8")).offsetMs) || 0; + } catch { + clockOffset = 0; + } + } + return real + clockOffset; +} + const { startServer } = await import("../server.mjs"); const draws = [0.999, 0, 0.999, 0.999, 0.999, 0]; let drawIndex = 0; // Tous les parcours et leurs deux comptes partagent la même adresse IP : la limite par minute les ferait échouer au hasard. -const server = startServer({ cardsApiOptions: { allowProductionDevAuth: true, apiRateLimit: 100_000, random: (max) => Math.min(max - 1, Math.floor(draws[drawIndex++ % draws.length] * max)) } }); +const server = startServer({ cardsApiOptions: { allowProductionDevAuth: true, apiRateLimit: 100_000, now, random: (max) => Math.min(max - 1, Math.floor(draws[drawIndex++ % draws.length] * max)) } }); let stopping = false; function stop() { diff --git a/services/cards/api.js b/services/cards/api.js index 0b64d8b..8bd485e 100644 --- a/services/cards/api.js +++ b/services/cards/api.js @@ -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; diff --git a/services/cards/catalog.js b/services/cards/catalog.js index 73a7cb3..f88cd25 100644 --- a/services/cards/catalog.js +++ b/services/cards/catalog.js @@ -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) { diff --git a/services/cards/content/expedition-destinations.json b/services/cards/content/expedition-destinations.json new file mode 100644 index 0000000..7270637 --- /dev/null +++ b/services/cards/content/expedition-destinations.json @@ -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 + } +] diff --git a/services/cards/database.js b/services/cards/database.js index 3e06188..000c97c 100644 --- a/services/cards/database.js +++ b/services/cards/database.js @@ -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); ` ]; diff --git a/services/cards/expedition-content.js b/services/cards/expedition-content.js new file mode 100644 index 0000000..439c979 --- /dev/null +++ b/services/cards/expedition-content.js @@ -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); +} diff --git a/services/cards/expedition-rules.js b/services/cards/expedition-rules.js new file mode 100644 index 0000000..dddf6be --- /dev/null +++ b/services/cards/expedition-rules.js @@ -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 } }; +} diff --git a/services/cards/expedition-service.js b/services/cards/expedition-service.js new file mode 100644 index 0000000..9099dca --- /dev/null +++ b/services/cards/expedition-service.js @@ -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 })) + }; + } +} diff --git a/services/cards/expedition-settings.js b/services/cards/expedition-settings.js new file mode 100644 index 0000000..1e24cfa --- /dev/null +++ b/services/cards/expedition-settings.js @@ -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; +} diff --git a/services/cards/expedition-simulation.js b/services/cards/expedition-simulation.js new file mode 100644 index 0000000..eb1ef9c --- /dev/null +++ b/services/cards/expedition-simulation.js @@ -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) } + }; +} diff --git a/services/cards/service.js b/services/cards/service.js index 997f517..d1a72b4 100644 --- a/services/cards/service.js +++ b/services/cards/service.js @@ -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); } diff --git a/tests/helpers/data-validation.mjs b/tests/helpers/data-validation.mjs index f59ee39..dd11718 100644 --- a/tests/helpers/data-validation.mjs +++ b/tests/helpers/data-validation.mjs @@ -242,6 +242,94 @@ export function validateSiteContent(site) { "cards.packs.giftDescription", "cards.packs.giftOpen", "cards.packs.noOpening", + "cards.guild.expeditionsKind", + "cards.guild.expeditionsTitle", + "cards.guild.expeditionsDescription", + "cards.guild.expeditionsToLaunch", + "cards.guild.expeditionsRunning", + "cards.guild.expeditionsReturned", + "cards.guild.expeditionsIdle", + "cards.guild.expeditionsNoCards", + "cards.guild.expeditionsClosed", + "cards.guild.expeditionsAction", + "cards.guild.expeditionsClaim", + "cards.guild.expeditionsOpen", + "cards.packs.giftFromExpedition", + "cards.expeditions.eyebrow", + "cards.expeditions.title", + "cards.expeditions.intro", + "cards.expeditions.back", + "cards.expeditions.eclatsBalance", + "cards.expeditions.eclatsHelp", + "cards.expeditions.closedTitle", + "cards.expeditions.closedText", + "cards.expeditions.expired", + "cards.expeditions.reload", + "cards.expeditions.activeTitle", + "cards.expeditions.reportMeta", + "cards.expeditions.running", + "cards.expeditions.returned", + "cards.expeditions.completed", + "cards.expeditions.cancelled", + "cards.expeditions.claim", + "cards.expeditions.claimed", + "cards.expeditions.started", + "cards.expeditions.rewardEclats", + "cards.expeditions.rewardStardust", + "cards.expeditions.rewardPacks", + "cards.expeditions.limitReached", + "cards.expeditions.planTitle", + "cards.expeditions.nextDay", + "cards.expeditions.noDestination", + "cards.expeditions.destinationsTitle", + "cards.expeditions.difficultyTitle", + "cards.expeditions.difficultyLabel", + "cards.expeditions.durationLabel", + "cards.expeditions.hours", + "cards.expeditions.requirementsTitle", + "cards.expeditions.main", + "cards.expeditions.conditionTag", + "cards.expeditions.conditionCollection", + "cards.expeditions.dangerText", + "cards.expeditions.or", + "cards.expeditions.teamTitle", + "cards.expeditions.teamHelp", + "cards.expeditions.roleBadge", + "cards.expeditions.slotEmpty", + "cards.expeditions.remove", + "cards.expeditions.cardsLabel", + "cards.expeditions.chooseCard", + "cards.expeditions.power", + "cards.expeditions.busy", + "cards.expeditions.noRole", + "cards.expeditions.noCards", + "cards.expeditions.previewTitle", + "cards.expeditions.previewEmpty", + "cards.expeditions.score", + "cards.expeditions.teamVersus", + "cards.expeditions.limitedByStars", + "cards.expeditions.conditionMet", + "cards.expeditions.conditionUnmet", + "cards.expeditions.dangerCountered", + "cards.expeditions.dangerActive", + "cards.expeditions.durationMalus", + "cards.expeditions.expected", + "cards.expeditions.start", + "cards.expeditions.tiers.struggle", + "cards.expeditions.tiers.success", + "cards.expeditions.tiers.triumph", + "cards.expeditions.stats.bravoure", + "cards.expeditions.stats.endurance", + "cards.expeditions.stats.fortune", + "cards.expeditions.stats.orientation", + "cards.expeditions.statShort.bravoure", + "cards.expeditions.statShort.endurance", + "cards.expeditions.statShort.fortune", + "cards.expeditions.statShort.orientation", + "cards.expeditions.roles.bravoure", + "cards.expeditions.roles.endurance", + "cards.expeditions.roles.fortune", + "cards.expeditions.roles.orientation", "guideChecklist.label", "guideChecklist.selectLabel", "guideChecklist.selectPlaceholder", diff --git a/tests/nebula-cards-expedition-balance.test.mjs b/tests/nebula-cards-expedition-balance.test.mjs new file mode 100644 index 0000000..14935cd --- /dev/null +++ b/tests/nebula-cards-expedition-balance.test.mjs @@ -0,0 +1,43 @@ +// Rôle : garde l'équilibre des Expéditions Sokko TCG avec le simulateur (seuils du document de conception). +// En cas d'échec après un ajout de cartes ou un changement de réglages : lancer `node scripts/simulate-expeditions.mjs` pour le détail. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { loadCardsCatalog } from "../services/cards/catalog.js"; +import { loadExpeditionDestinations } from "../services/cards/expedition-content.js"; +import { DEFAULT_EXPEDITION_SETTINGS, mergeExpeditionSettings } from "../services/cards/expedition-settings.js"; +import { simulate } from "../services/cards/expedition-simulation.js"; + +const catalog = loadCardsCatalog("website/public/data/cards/catalog.json"); +const destinations = loadExpeditionDestinations("services/cards/content/expedition-destinations.json", catalog); +const settings = mergeExpeditionSettings(DEFAULT_EXPEDITION_SETTINGS, destinations.map((destination) => destination.id)); +const report = simulate(catalog, destinations, settings); +const row = (level, rarity, stars) => report.byRarity.find((item) => item.level === level && item.rarity === rarity && item.stars === stars); + +test("every rare or better card reaches Réussite at 2 stars somewhere at level 0", () => { + const weak = report.cardBest.filter((card) => card.scorePct < settings.score.successPct); + assert.deepEqual(weak.map((card) => `${card.cardId} (${card.rarity}) ${card.scorePct.toFixed(0)} %`), []); +}); + +test("expected loot per hour is the same for every duration", () => { + for (const { stars, tier, perHour } of report.lootPerHour) { + assert.ok(perHour.every((value) => Math.abs(value - perHour[0]) < 1e-9), `${stars} ★ ${tier}`); + } +}); + +test("a rare and a mythic end within 5 % of each other at the cap", () => { + const { rare, mythic } = report.rareVsMythicAtMax; + assert.ok(Math.abs(rare - mythic) / mythic <= 0.05); +}); + +test("rarer cards never score lower than commoner ones at the same level and stars", () => { + const order = ["rare", "epic", "legendary", "mythic"]; + for (let stars = 1; stars <= 5; stars += 1) { + const medians = order.map((rarity) => row("niveau 0", rarity, stars).median); + for (let index = 1; index < medians.length; index += 1) assert.ok(medians[index] >= medians[index - 1], `${order[index]} ${stars} ★`); + } +}); + +test("4 stars stay out of reach for level 0 rares but open to capped cards", () => { + assert.ok(row("niveau 0", "rare", 4).max < settings.score.successPct, "a level 0 rare pair reaches Réussite at 4 stars"); + assert.ok(report.triumphShareAt4 >= 0.5, `only ${(report.triumphShareAt4 * 100).toFixed(0)} % of destinations allow a capped rare pair to triumph at 4 stars`); +}); diff --git a/tests/nebula-cards-expedition-service.test.mjs b/tests/nebula-cards-expedition-service.test.mjs new file mode 100644 index 0000000..67e3242 --- /dev/null +++ b/tests/nebula-cards-expedition-service.test.mjs @@ -0,0 +1,240 @@ +// Rôle : vérifie le service et l'API des Expéditions Sokko TCG (destinations du jour, départ solo, retour, réglages, suppression de compte). +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import { Readable } from "node:stream"; +import { test } from "node:test"; +import { createCardsApiHandler } from "../services/cards/api.js"; +import { buildPublishedCatalog, prepareVersionedCatalog } from "../services/cards/catalog.js"; +import { INITIAL_COLLECTION_STATES, INITIAL_DROP_RATES } from "../services/cards/admin-seed.js"; +import { CardsDatabase } from "../services/cards/database.js"; +import { CardsService } from "../services/cards/service.js"; + +const baseCatalog = prepareVersionedCatalog(JSON.parse(await readFile("website/public/data/cards/catalog.json", "utf8"))); +const published = buildPublishedCatalog(baseCatalog, { collectionStates: INITIAL_COLLECTION_STATES, dropRates: INITIAL_DROP_RATES }); +const HOUR = 3_600_000; +const rarityOf = (cardId) => published.editions.find((edition) => edition.cardId === cardId && !edition.promotional).rarity; +const editionsOf = (rarity, collectionId = "primordial-nebula") => published.editions + .filter((edition) => edition.rarity === rarity && published.cards.find((card) => card.id === edition.cardId).collectionId === collectionId) + .map((edition) => edition.id); + +function expeditionService({ start = Date.parse("2026-11-15T09:00:00Z"), random = () => 0 } = {}) { + const clock = { now: start }; + const database = new CardsDatabase(":memory:"); + const service = new CardsService({ database, catalog: baseCatalog, now: () => clock.now, random }); + const admin = service.upsertPlayer({ discordId: "expedition-admin", displayName: "Admin", isAdmin: true }); + const player = service.upsertPlayer({ discordId: "expedition-player", displayName: "Player" }); + const open = (changes = {}) => service.expeditions.updateSettings(admin.id, { ...service.expeditions.settings, enabled: true, ...changes }); + const rares = editionsOf("rare"); + database.transaction(() => rares.slice(0, 4).forEach((editionId) => service.addCard(player.id, editionId))); + return { clock, database, service, admin, player, open, rares }; +} + +const soloBody = (view, slots, changes = {}) => ({ day: view.day, destinationId: view.destinations[0].id, difficulty: 1, durationHours: 2, slots, ...changes }); + +test("expeditions stay closed until an administrator opens them", () => { + const { service, player, open, rares } = expeditionService(); + const closed = service.expeditions.getExpeditions(player.id); + assert.equal(closed.enabled, false); + assert.deepEqual(closed.destinations, []); + assert.equal(service.getState(player.id).expeditions.enabled, false); + assert.throws(() => service.expeditions.startSolo(player.id, soloBody({ day: closed.day, destinations: [{ id: "light-currents" }] }, rares.slice(0, 2)), "k1"), (error) => error.code === "EXPEDITIONS_CLOSED"); + assert.throws(() => service.expeditions.updateSettings(player.id, { ...service.expeditions.settings, enabled: true }), (error) => error.code === "ADMIN_REQUIRED"); + open(); + const view = service.expeditions.getExpeditions(player.id); + assert.equal(view.enabled, true); + assert.equal(view.day, "2026-11-15"); + assert.equal(view.destinations.length, 4); + assert.deepEqual(Object.keys(view.destinations[0].stars), ["1", "2", "3", "4"]); + assert.equal(view.destinations[0].stars[4].dangers.length, 1); + assert.equal(view.destinations[0].stars[2].condition, null); + assert.equal(view.cards.length, 4); + // Le tirage du jour est commun à tous et gardé en base. + assert.deepEqual(service.expeditions.getExpeditions(player.id).destinations.map((item) => item.id), view.destinations.map((item) => item.id)); +}); + +test("a solo expedition freezes its team, hides its result until it returns and pays once", () => { + const { clock, service, player, open, rares, database } = expeditionService(); + open(); + const view = service.expeditions.getExpeditions(player.id); + const body = soloBody(view, rares.slice(0, 2), { difficulty: 2, durationHours: 6 }); + const preview = service.expeditions.preview(player.id, body).preview; + assert.ok(["struggle", "success", "triumph"].includes(preview.tier)); + assert.equal(preview.requirements.length, 2); + assert.ok(preview.expected.eclats > 0); + + const started = service.expeditions.startSolo(player.id, body, "start-1"); + assert.equal(started.expedition.status, "running"); + assert.equal(started.expedition.result, null); + assert.equal(started.expedition.reward, null); + assert.equal(started.expedition.returnsAt, clock.now + 6 * HOUR); + assert.equal(started.state.expeditions.running, 1); + assert.equal(started.state.expeditions.launchedToday, true); + assert.deepEqual(started.state.expeditions.busyEditions.map((item) => item.editionId).sort(), rares.slice(0, 2).sort()); + // Même clé : même expédition ; nouvelle clé : la limite solo s'applique, et les cartes sont occupées. + assert.equal(service.expeditions.startSolo(player.id, body, "start-1").expedition.id, started.expedition.id); + assert.throws(() => service.expeditions.startSolo(player.id, body, "start-2"), (error) => error.code === "EXPEDITION_CARD_BUSY"); + assert.throws(() => service.expeditions.startSolo(player.id, { ...body, slots: rares.slice(2, 4) }, "start-3"), (error) => error.code === "EXPEDITION_LIMIT"); + assert.throws(() => service.expeditions.claim(player.id, started.expedition.id), (error) => error.code === "EXPEDITION_NOT_RETURNED"); + + // Une amélioration des réglages pendant le trajet ne change rien : tout est figé au départ. + clock.now += 6 * HOUR; + const before = service.getState(player.id); + assert.equal(before.expeditions.returned, 1); + const returned = service.expeditions.getExpeditions(player.id).expeditions[0]; + assert.equal(returned.status, "returned"); + assert.equal(returned.result.tier, preview.tier); + const claimed = service.expeditions.claim(player.id, started.expedition.id); + assert.equal(claimed.expedition.status, "completed"); + assert.equal(claimed.state.wallet.eclats, returned.reward.eclats); + assert.equal(claimed.state.wallet.stardust, before.wallet.stardust + returned.reward.stardust); + assert.ok(returned.reward.eclats >= Math.floor(preview.expected.eclats)); + // random() = 0 : tous les tirages réussissent, donc un paquet rapporté, rangé avec les paquets offerts. + assert.equal(returned.reward.packs.length, 1); + assert.equal(claimed.state.giftPacks.length, 1); + assert.equal(claimed.state.giftPacks[0].source, "expedition"); + assert.equal(claimed.state.giftPacks[0].sourceName, returned.destination.name); + const history = claimed.state.history.find((entry) => entry.type === "expedition_completed"); + assert.equal(history.details.eclats, returned.reward.eclats); + // Deuxième retour : même rapport, aucun crédit en plus ; les cartes sont libres. + const again = service.expeditions.claim(player.id, started.expedition.id); + assert.equal(again.state.wallet.eclats, claimed.state.wallet.eclats); + assert.deepEqual(again.state.expeditions.busyEditions, []); + assert.equal(database.db.prepare("SELECT COUNT(*) AS count FROM gift_packs WHERE source = 'expedition'").get().count, 1); + // Le paquet rapporté s'ouvre comme un paquet offert. + const opened = service.openGiftPack(player.id, claimed.state.giftPacks[0].id, "open-expedition-pack"); + assert.equal(opened.opening.cards.length, 3); +}); + +test("unlucky rolls keep the average and never hand out a pack", () => { + const { clock, service, player, open, rares } = expeditionService({ random: (max) => max - 1 }); + open(); + const view = service.expeditions.getExpeditions(player.id); + const started = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "unlucky"); + clock.now += 2 * HOUR; + const returned = service.expeditions.claim(player.id, started.expedition.id).expedition; + assert.deepEqual(returned.reward.packs, []); + assert.equal(returned.reward.eclats, Math.floor(returned.reward.eclats)); +}); + +test("solo departures refuse stale days, unknown destinations, commons, duplicates and cards the player lacks", () => { + const { clock, service, player, open, rares } = expeditionService(); + open(); + const view = service.expeditions.getExpeditions(player.id); + const start = (changes, key) => () => service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2), changes), key); + assert.throws(start({ destinationId: "nowhere" }, "a"), (error) => error.code === "EXPEDITION_INVALID"); + assert.throws(start({ difficulty: 5 }, "b"), (error) => error.code === "EXPEDITION_INVALID"); + assert.throws(start({ durationHours: 3 }, "c"), (error) => error.code === "EXPEDITION_INVALID"); + assert.throws(start({ slots: [rares[0]] }, "d"), (error) => error.code === "EXPEDITION_CARD_INVALID"); + assert.throws(start({ slots: [rares[0], rares[0]] }, "e"), (error) => error.code === "EXPEDITION_CARD_INVALID"); + assert.throws(start({ slots: [rares[0], editionsOf("common")[0]] }, "f"), (error) => error.code === "EXPEDITION_CARD_INVALID"); + assert.throws(start({ slots: [rares[0], rares[10]] }, "g"), (error) => error.code === "CARD_NOT_OWNED"); + assert.throws(() => service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), ""), (error) => error.code === "IDEMPOTENCY_REQUIRED"); + clock.now += 24 * HOUR; + assert.throws(start({}, "h"), (error) => error.code === "EXPEDITION_DAY_EXPIRED"); + assert.equal(rarityOf("starvoid-dragon"), "legendary"); +}); + +test("administrators tune settings with bounds and history, and can cancel an expedition", () => { + const { service, admin, player, open, rares, database } = expeditionService(); + assert.throws(() => service.expeditions.updateSettings(admin.id, { ...service.expeditions.settings, score: { ...service.expeditions.settings.score, successPct: 500 } }), (error) => error.code === "EXPEDITION_SETTINGS_INVALID"); + open(); + assert.throws(() => open(), (error) => error.code === "EXPEDITION_SETTINGS_UNCHANGED"); + const audit = database.db.prepare("SELECT details_json FROM audit_log WHERE event_type = 'expedition_settings_updated'").get(); + assert.deepEqual(JSON.parse(audit.details_json).changes, [{ path: "enabled", previous: false, next: true }]); + assert.ok(service.getAdminHistory(admin.id).entries.some((entry) => entry.type === "expedition_settings_updated")); + const dashboard = service.getAdminDashboard(admin.id); + assert.equal(dashboard.expeditionSettings.settings.enabled, true); + assert.equal(dashboard.expeditionSettings.destinations.length, 12); + assert.ok(dashboard.expeditionSettings.schema.some((field) => field.path === "loot.eclatsPerHourCents")); + + const view = service.expeditions.getExpeditions(player.id); + const started = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "cancel-me"); + assert.equal(service.getAdminDashboard(admin.id).expeditionsToday.running, 1); + assert.throws(() => service.expeditions.cancel(player.id, started.expedition.id), (error) => error.code === "ADMIN_REQUIRED"); + service.expeditions.cancel(admin.id, started.expedition.id); + const state = service.getState(player.id); + assert.deepEqual(state.expeditions.busyEditions, []); + assert.ok(state.history.some((entry) => entry.type === "expedition_cancelled_by_guild")); + assert.throws(() => service.expeditions.claim(player.id, started.expedition.id), (error) => error.code === "EXPEDITION_NOT_FOUND"); + assert.throws(() => service.expeditions.cancel(admin.id, started.expedition.id), (error) => error.code === "EXPEDITION_FINISHED"); +}); + +test("deleting an account cancels its expeditions and resets its Éclats", () => { + const { clock, service, player, open, rares, database } = expeditionService(); + open(); + const view = service.expeditions.getExpeditions(player.id); + const first = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(0, 2)), "first"); + clock.now += 2 * HOUR; + service.expeditions.claim(player.id, first.expedition.id); + const second = service.expeditions.startSolo(player.id, soloBody(view, rares.slice(2, 4)), "second"); + service.deleteAccount(player.id); + assert.equal(database.db.prepare("SELECT eclats FROM players WHERE id = ?").get(player.id).eclats, 0); + assert.equal(database.db.prepare("SELECT status FROM expeditions WHERE id = ?").get(second.expedition.id).status, "cancelled"); +}); + +function mockRequest({ method = "GET", path, body, headers = {} }) { + const req = Readable.from(body == null ? [] : [Buffer.from(JSON.stringify(body))]); + req.method = method; + req.url = path; + req.headers = { host: "localhost:5173", ...headers }; + req.socket = { remoteAddress: "127.0.0.1" }; + return req; +} + +async function call(handler, options) { + const response = { status: 0, headers: {}, chunks: [] }; + const res = { + setHeader(name, value) { response.headers[name.toLowerCase()] = value; }, + writeHead(status, headers = {}) { + response.status = status; + for (const [name, value] of Object.entries(headers)) response.headers[name.toLowerCase()] = value; + }, + end(value = "") { response.chunks.push(Buffer.from(value)); } + }; + await handler(mockRequest(options), res); + response.raw = Buffer.concat(response.chunks); + response.json = response.headers["content-type"]?.startsWith("application/json") && response.raw.length ? JSON.parse(response.raw.toString("utf8")) : null; + return response; +} + +test("the expeditions API requires a session, CSRF protection, an administrator for settings and an idempotency key to start", async (t) => { + const handler = createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth: true, databasePath: ":memory:", env: { NODE_ENV: "test" }, random: () => 0 }); + t.after(() => handler.close()); + assert.equal((await call(handler, { path: "/api/cards/expeditions" })).status, 401); + const login = await call(handler, { method: "POST", path: "/api/cards/auth/dev", body: {} }); + const cookie = login.headers["set-cookie"].split(";")[0]; + const headers = { cookie, "x-csrf-token": login.json.csrfToken }; + const closed = await call(handler, { path: "/api/cards/expeditions", headers: { cookie } }); + assert.equal(closed.status, 200); + assert.equal(closed.json.enabled, false); + + assert.equal((await call(handler, { method: "PUT", path: "/api/cards/admin/expeditions/settings", headers: { cookie }, body: {} })).status, 403); + const dashboard = await call(handler, { path: "/api/cards/admin/dashboard", headers: { cookie } }); + const settings = { ...dashboard.json.expeditionSettings.settings, enabled: true }; + const invalid = await call(handler, { method: "PUT", path: "/api/cards/admin/expeditions/settings", headers, body: { settings: { ...settings, solo: { ...settings.solo, maxStars: 9 } } } }); + assert.equal(invalid.status, 400); + assert.equal(invalid.json.error.code, "EXPEDITION_SETTINGS_INVALID"); + const opened = await call(handler, { method: "PUT", path: "/api/cards/admin/expeditions/settings", headers, body: { settings } }); + assert.equal(opened.status, 200); + assert.equal(opened.json.expeditionSettings.settings.enabled, true); + + const devId = handler.service.db.prepare("SELECT id FROM players WHERE discord_id = 'dev-admin'").get().id; + handler.service.database.transaction(() => editionsOf("rare").slice(0, 2).forEach((editionId) => handler.service.addCard(devId, editionId))); + const view = (await call(handler, { path: "/api/cards/expeditions", headers: { cookie } })).json; + const slots = view.cards.slice(0, 2).map((card) => card.editionId); + assert.equal(slots.length, 2, "the development account owns rare or better cards"); + const body = soloBody(view, slots); + const preview = await call(handler, { method: "POST", path: "/api/cards/expeditions/preview", headers, body }); + assert.equal(preview.status, 200); + const noKey = await call(handler, { method: "POST", path: "/api/cards/expeditions", headers, body }); + assert.equal(noKey.json.error.code, "IDEMPOTENCY_REQUIRED"); + const started = await call(handler, { method: "POST", path: "/api/cards/expeditions", headers: { ...headers, "idempotency-key": "api-start" }, body }); + assert.equal(started.status, 201); + assert.equal(started.json.expedition.status, "running"); + const early = await call(handler, { method: "POST", path: `/api/cards/expeditions/${started.json.expedition.id}/claim`, headers }); + assert.equal(early.status, 409); + assert.equal(early.json.error.code, "EXPEDITION_NOT_RETURNED"); + const cancelled = await call(handler, { method: "POST", path: `/api/cards/admin/expeditions/${started.json.expedition.id}/cancel`, headers }); + assert.equal(cancelled.status, 200); +}); diff --git a/tests/nebula-cards-expeditions.test.mjs b/tests/nebula-cards-expeditions.test.mjs new file mode 100644 index 0000000..c9eb57a --- /dev/null +++ b/tests/nebula-cards-expeditions.test.mjs @@ -0,0 +1,222 @@ +// Rôle : vérifie les données, les réglages et les règles pures des Expéditions Sokko TCG. +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { test } from "node:test"; +import { prepareVersionedCatalog } from "../services/cards/catalog.js"; +import { loadExpeditionDestinations, validateExpeditionDestinations } from "../services/cards/expedition-content.js"; +import { + applyHazards, cardPower, drawExpeditionDay, editionExpeditionData, efficiency, evaluateTeam, expectedLoot, maxLevel, + requirementsFor, resolveDayEntry, rollLoot, roundStochastic, scoreExpedition, soloRoles, splitPower, STAT_IDS, teamStats +} from "../services/cards/expedition-rules.js"; +import { + DEFAULT_EXPEDITION_SETTINGS, diffExpeditionSettings, EXPEDITION_SETTINGS_SCHEMA, mergeExpeditionSettings, readPath, validateExpeditionSettings +} from "../services/cards/expedition-settings.js"; +import { EXPEDITION_SETTING_GROUPS, expeditionSettingLabel } from "../website/src/features/cards/admin/expeditionSettingFields.js"; +import { expeditionsPending, guildQuests } from "../website/src/features/cards/guildQuests.js"; + +const rawCatalog = JSON.parse(await readFile("website/public/data/cards/catalog.json", "utf8")); +const catalog = prepareVersionedCatalog(rawCatalog); +const destinationsPath = "services/cards/content/expedition-destinations.json"; +const destinations = loadExpeditionDestinations(destinationsPath, catalog); +const destinationIds = destinations.map((destination) => destination.id); +const settings = mergeExpeditionSettings(DEFAULT_EXPEDITION_SETTINGS, destinationIds); +const profile = (bravoure, endurance, fortune, orientation) => ({ bravoure, endurance, fortune, orientation }); + +test("every catalog card carries expedition tags and every collection a profile", () => { + const tagIds = new Set(rawCatalog.expeditionTags.map((tag) => tag.id)); + assert.ok(rawCatalog.cards.every((card) => card.expedition.tags.length >= 1 && card.expedition.tags.every((tag) => tagIds.has(tag)))); + assert.ok(rawCatalog.collections.every((collection) => STAT_IDS.reduce((sum, stat) => sum + collection.expedition.profile[stat], 0) === 100)); + // Aucune étiquette inutilisée : le vocabulaire reste celui des cartes. + const used = new Set(rawCatalog.cards.flatMap((card) => card.expedition.tags)); + assert.deepEqual(rawCatalog.expeditionTags.filter((tag) => !used.has(tag.id)), []); +}); + +test("catalog validation refuses broken expedition data", () => { + const unknownTag = structuredClone(rawCatalog); + unknownTag.cards[0].expedition.tags = ["theme:inconnu"]; + assert.throws(() => prepareVersionedCatalog(unknownTag), /unknown expedition tag theme:inconnu/); + const noTags = structuredClone(rawCatalog); + delete noTags.cards[0].expedition; + assert.throws(() => prepareVersionedCatalog(noTags), /needs 1 to 8 expedition tags/); + const repeated = structuredClone(rawCatalog); + repeated.cards[0].expedition.tags = ["theme:voyage", "theme:voyage"]; + assert.throws(() => prepareVersionedCatalog(repeated), /repeats an expedition tag/); + const badProfile = structuredClone(rawCatalog); + badProfile.cards[0].expedition.profile = profile(50, 50, 10, 0); + assert.throws(() => prepareVersionedCatalog(badProfile), /summing to 100/); + const noCollectionProfile = structuredClone(rawCatalog); + delete noCollectionProfile.collections[0].expedition; + assert.throws(() => prepareVersionedCatalog(noCollectionProfile), /needs an expedition profile/); + const badTagId = structuredClone(rawCatalog); + badTagId.expeditionTags.push({ id: "Voyage", label: "Voyage" }); + assert.throws(() => prepareVersionedCatalog(badTagId), /family:name id/); +}); + +test("destinations order the four stats and stay satisfiable by rare or better cards", () => { + assert.equal(destinations.length, 12); + // Une destination par couple (stat principale, seconde stat) : chaque paire de rôles du solo existe. + assert.equal(new Set(destinations.map((destination) => destination.stats.slice(0, 2).join("+"))).size, 12); + const broken = (change) => { + const copy = structuredClone(destinations); + change(copy[0]); + return () => validateExpeditionDestinations(copy, catalog); + }; + assert.throws(broken((destination) => { destination.stats = ["bravoure", "bravoure", "fortune", "orientation"]; }), /order the four stats/); + assert.throws(broken((destination) => { destination.conditions = [{ type: "tag", tag: "personnage:ours" }]; }), /fewer than 3/); + assert.throws(broken((destination) => { destination.dangers[0].unlessTags = ["theme:inconnu"]; }), /known counter tags/); + assert.throws(broken((destination) => { destination.coverCardId = "missing"; }), /unknown cover card/); + assert.throws(() => validateExpeditionDestinations(destinations.map((destination) => ({ ...destination, hidden: true })), catalog), /visible destination/); +}); + +test("expedition settings merge stored values with defaults and validate bounds and cross rules", () => { + assert.equal(validateExpeditionSettings(settings, destinationIds), null); + assert.equal(settings.enabled, false); + assert.deepEqual(settings.destinations[destinationIds[0]], { active: true, weight: 1 }); + // Champ manquant ou invalide : valeur par défaut, signalée ; clé inconnue : supprimée. + const invalid = []; + const merged = mergeExpeditionSettings({ power: { rare: 45, cap: "x" }, extra: 1, destinations: { [destinationIds[0]]: { active: false, weight: 3 }, gone: { active: true, weight: 1 } } }, destinationIds, (path) => invalid.push(path)); + assert.equal(merged.power.rare, 45); + assert.equal(merged.power.cap, 100); + assert.deepEqual(invalid, ["power.cap"]); + assert.equal("extra" in merged, false); + assert.equal("gone" in merged.destinations, false); + assert.deepEqual(merged.destinations[destinationIds[0]], { active: false, weight: 3 }); + // Chaque champ du schéma a une valeur par défaut valide. + for (const field of EXPEDITION_SETTINGS_SCHEMA) assert.notEqual(readPath(DEFAULT_EXPEDITION_SETTINGS, field.path), undefined, field.path); + + const withChange = (path, value) => { + const copy = structuredClone(settings); + const keys = path.split("."); + keys.slice(0, -1).reduce((node, key) => node[key], copy)[keys.at(-1)] = value; + return copy; + }; + assert.match(validateExpeditionSettings(withChange("day.destinationsPerDay", 0), destinationIds), /day\.destinationsPerDay/); + assert.match(validateExpeditionSettings(withChange("durations.hours", [6, 2, 12]), destinationIds), /croissantes/); + assert.match(validateExpeditionSettings(withChange("requirements.star3", [1, 2]), destinationIds), /3 entiers/); + assert.match(validateExpeditionSettings(withChange("score.successPct", 130), destinationIds), /Réussite < Triomphe/); + assert.match(validateExpeditionSettings(withChange("solo.minStars", 5), destinationIds), /étoile minimale/); + assert.match(validateExpeditionSettings(withChange("power.rare", 120), destinationIds), /plafond/); + assert.match(validateExpeditionSettings(withChange("destinations", { unknown: { active: true, weight: 1 } }), destinationIds), /inconnue/); + + const next = withChange("loot.eclatsPerHourCents", 300); + next.destinations[destinationIds[1]].weight = 4; + assert.deepEqual(diffExpeditionSettings(settings, next), [ + { path: "loot.eclatsPerHourCents", previous: 200, next: 300 }, + { path: `destinations.${destinationIds[1]}.weight`, previous: 1, next: 4 } + ]); +}); + +test("power grows with levels up to the shared cap and splits exactly by profile", () => { + assert.equal(cardPower("rare", 0, settings), 40); + assert.equal(cardPower("rare", 4, settings), 60); + assert.equal(cardPower("rare", 99, settings), 100); + assert.equal(cardPower("common", 3, settings), 0); + assert.deepEqual(["rare", "epic", "legendary", "mythic"].map((rarity) => maxLevel(rarity, settings)), [12, 9, 6, 3]); + assert.deepEqual(splitPower(40, profile(25, 25, 20, 30)), { bravoure: 10, endurance: 10, fortune: 8, orientation: 12 }); + const odd = splitPower(55, profile(33, 33, 17, 17)); + assert.equal(Object.values(odd).reduce((sum, value) => sum + value, 0), 55); + // Une mythique garde sa propre rareté, mais le profil et les étiquettes de sa carte. + const legendary = editionExpeditionData(catalog, "starvoid-dragon-standard", 0, settings); + assert.equal(legendary.power, 70); + assert.deepEqual(legendary.tags, ["personnage:dragon", "lieu:nebuleuse", "lieu:soleil"]); + assert.equal(editionExpeditionData(catalog, "dragon-constellation-standard", 0, settings), null); +}); + +test("requirements scale per slot, roles double a stat, hazards and conditions weigh on the score", () => { + const destination = destinations.find((item) => item.id === "light-currents"); + const roles = soloRoles(destination, 2); + assert.deepEqual(roles, ["orientation", "bravoure"]); + assert.deepEqual(requirementsFor(destination, 2, roles, settings), [ + { stat: "orientation", main: true, value: 33 }, + { stat: "bravoure", main: false, value: 30 } + ]); + // Une place sans rôle (Veilleur de la Guilde) n'ajoute que sa part. + assert.equal(requirementsFor(destination, 1, ["orientation", null, null, null], settings)[0].value, 45); + + const slot = { stats: { bravoure: 10, endurance: 10, fortune: 10, orientation: 10 }, tags: [], collectionId: "primordial-nebula" }; + assert.deepEqual(teamStats([{ ...slot, role: "orientation" }, { ...slot, role: null }], settings), { bravoure: 20, endurance: 20, fortune: 20, orientation: 30 }); + + // 12 h sans Endurance : −15 % ; Endurance suffisante : aucun malus. Danger non paré : −20 %, moins le bouclier. + assert.equal(applyHazards({ bravoure: 10, endurance: 0, fortune: 10, orientation: 10 }, { slotCount: 2, durationIndex: 2 }, settings).durationFactor, 0.85); + assert.equal(applyHazards({ bravoure: 10, endurance: 24, fortune: 10, orientation: 10 }, { slotCount: 2, durationIndex: 2 }, settings).durationFactor, 1); + const danger = { id: "d", label: "D", stat: "bravoure", unlessTags: ["theme:hiver"] }; + assert.equal(applyHazards({ bravoure: 10, endurance: 0, fortune: 0, orientation: 0 }, { slotCount: 2, durationIndex: 0, dangers: [{ ...danger, countered: false }] }, settings).stats.bravoure, 8); + assert.equal(applyHazards({ bravoure: 10, endurance: 28, fortune: 0, orientation: 0 }, { slotCount: 2, durationIndex: 0, dangers: [{ ...danger, countered: false }] }, settings).stats.bravoure, 9); + assert.equal(applyHazards({ bravoure: 10, endurance: 0, fortune: 0, orientation: 0 }, { slotCount: 2, durationIndex: 0, dangers: [{ ...danger, countered: true }] }, settings).stats.bravoure, 10); + + assert.equal(efficiency(0.5, settings), 0.5); + assert.equal(efficiency(1.5, settings), 1.25); + assert.equal(efficiency(3, settings), 1.5); + const requirements = [{ stat: "bravoure", main: true, value: 10 }, { stat: "fortune", main: false, value: 10 }]; + const full = scoreExpedition({ requirements, stats: { bravoure: 10, fortune: 10 } }, settings); + assert.equal(full.scorePct, 100); + assert.equal(full.tier, "success"); + assert.equal(scoreExpedition({ requirements, stats: { bravoure: 10, fortune: 10 }, conditionMet: false }, settings).scorePct, 75); + assert.equal(scoreExpedition({ requirements, stats: { bravoure: 40, fortune: 40 } }, settings).tier, "triumph"); + assert.equal(scoreExpedition({ requirements, stats: { bravoure: 5, fortune: 5 } }, settings).tier, "struggle"); +}); + +test("one more star never raises the score of the same team", () => { + const destination = destinations[0]; + const entry = { condition: destination.conditions[0], dangers: destination.dangers }; + // Équipe faible sur la stat principale, forte sur la seconde : sans la règle, 2 ★ ferait mieux que 1 ★. + const slots = [ + { stats: { bravoure: 40, endurance: 0, fortune: 0, orientation: 4 }, role: destination.stats[0], tags: [], collectionId: "primordial-nebula" }, + { stats: { bravoure: 40, endurance: 0, fortune: 0, orientation: 4 }, role: destination.stats[1], tags: [], collectionId: "primordial-nebula" } + ]; + const scores = [1, 2, 3, 4].map((stars) => evaluateTeam({ destination, entry, stars, durationIndex: 0, slots }, settings)); + for (let index = 1; index < scores.length; index += 1) assert.ok(scores[index].scorePct <= scores[index - 1].scorePct); + assert.equal(scores[1].limitedByStars, 1); +}); + +test("loot is proportional to the chosen duration and rounds without changing its average", () => { + const short = expectedLoot({ hours: 2, stars: 2, tier: "success", fortune: 0, slotCount: 2 }, settings); + const long = expectedLoot({ hours: 12, stars: 2, tier: "success", fortune: 0, slotCount: 2 }, settings); + assert.equal(long.eclats / 12, short.eclats / 2); + assert.equal(short.eclats, 5.2); + // Fortune : +2 % par point moyen par place, plafonné ; destinations bonus : multiplicateur propre. + assert.equal(expectedLoot({ hours: 2, stars: 1, tier: "success", fortune: 20, slotCount: 2 }, settings).fortuneBonusPct, 20); + assert.equal(expectedLoot({ hours: 2, stars: 1, tier: "success", fortune: 200, slotCount: 2 }, settings).fortuneBonusPct, 50); + assert.equal(expectedLoot({ hours: 4, stars: 1, tier: "success", fortune: 0, slotCount: 2, bonusSlot: 6 }, settings).eclats, 10); + assert.equal(roundStochastic(2.3, () => 0), 3); + assert.equal(roundStochastic(2.3, (max) => max - 1), 2); + assert.equal(roundStochastic(4, () => 0), 4); + assert.deepEqual(rollLoot({ eclats: 1.5, stardust: 0.2, packs: 5 }, settings, () => 0), { eclats: 2, stardust: 1, packs: 2 }); +}); + +test("the day draw picks active visible destinations and avoids yesterday's when it can", () => { + const draw = drawExpeditionDay(destinations, settings, [], () => 0); + assert.equal(draw.length, 4); + assert.equal(new Set(draw.map((entry) => entry.destinationId)).size, 4); + const recent = draw.map((entry) => entry.destinationId); + const next = drawExpeditionDay(destinations, settings, recent, () => 0); + assert.ok(next.every((entry) => !recent.includes(entry.destinationId))); + // Destinations retirées ou de poids nul : jamais tirées. + const closed = structuredClone(settings); + for (const id of destinationIds.slice(1)) closed.destinations[id].active = false; + assert.deepEqual(drawExpeditionDay(destinations, closed, [destinationIds[0]], () => 0).map((entry) => entry.destinationId), [destinationIds[0]]); + // Le second danger diffère du premier quand la destination en a deux. + assert.ok(draw.every((entry) => entry.dangerIndexes[0] !== entry.dangerIndexes[1])); + const resolved = resolveDayEntry(destinations, draw[0]); + assert.equal(resolved.entry.dangers.length, 2); + assert.equal(resolveDayEntry(destinations, { destinationId: "missing", conditionIndex: 0, dangerIndexes: [0, 0] }), null); +}); + +test("every server setting has its label in the administration, and nothing else", () => { + const labelled = EXPEDITION_SETTING_GROUPS.flatMap((group) => group.fields.map((field) => field.path)); + assert.deepEqual([...labelled].sort(), EXPEDITION_SETTINGS_SCHEMA.map((field) => field.path).sort()); + assert.equal(expeditionSettingLabel(`destinations.${destinations[0].id}.weight`, destinations), `${destinations[0].name} · poids`); +}); + +test("the guild shows expeditions when open and flags them once a day or when one is back", () => { + const now = Date.parse("2026-11-15T10:00:00Z"); + const summary = { enabled: true, running: 0, returned: 0, nextReturnAt: null, launchedToday: false, eligible: 3, soloCards: 2, busyEditions: [] }; + assert.equal(expeditionsPending(summary, now), true); + assert.equal(expeditionsPending({ ...summary, launchedToday: true }, now), false); + assert.equal(expeditionsPending({ ...summary, eligible: 1 }, now), false); + assert.equal(expeditionsPending({ ...summary, running: 1, launchedToday: true, nextReturnAt: now + 1000 }, now), false); + assert.equal(expeditionsPending({ ...summary, running: 1, launchedToday: true, nextReturnAt: now - 1000 }, now), true); + // Fermées : la tuile disparaît, sauf tant qu'une expédition du joueur n'est pas terminée. + assert.deepEqual(guildQuests({ expeditions: { ...summary, enabled: false } }, now), []); + assert.equal(guildQuests({ expeditions: { ...summary, enabled: false, returned: 1 } }, now)[0].pending, true); +}); diff --git a/tests/nebula-cards.test.mjs b/tests/nebula-cards.test.mjs index d67c593..43f5dff 100644 --- a/tests/nebula-cards.test.mjs +++ b/tests/nebula-cards.test.mjs @@ -494,7 +494,7 @@ test("duplicates become stardust that buys openings kept apart from the recharge const value = INITIAL_SHOP_SETTING.stardustValues[rarity]; const before = service.getState(player.id); - assert.deepEqual(before.wallet, { stardust: 0, purchasedOpenings: 0 }); + assert.deepEqual(before.wallet, { stardust: 0, purchasedOpenings: 0, eclats: 0 }); assert.deepEqual(before.shop, { stardustValues: INITIAL_SHOP_SETTING.stardustValues, openingPrice: INITIAL_SHOP_SETTING.openingPrice, shopPackPrice: 60, shopPackShare: 50, dailyReward: 10 }); assert.deepEqual(before.recycling, { count: 2, stardust: 2 * value }); // Une favorite garde son exemplaire : ses doublons se recyclent comme les autres. @@ -520,7 +520,7 @@ test("duplicates become stardust that buys openings kept apart from the recharge // Vide les ouvertures de bienvenue restantes sans changer la collection vérifiée plus bas. database.db.prepare("UPDATE players SET openings_balance = 0 WHERE id = ?").run(player.id); const bought = service.buyOpening(player.id); - assert.deepEqual(bought.wallet, { stardust: 0, purchasedOpenings: 1 }); + assert.deepEqual(bought.wallet, { stardust: 0, purchasedOpenings: 1, eclats: 0 }); assert.throws(() => service.buyOpening(player.id), /Pas assez/); // La réserve est vide : seule l'ouverture achetée permet d'ouvrir, sans toucher à la réserve. diff --git a/tests/static-styles.test.mjs b/tests/static-styles.test.mjs index 34b6696..862e5ef 100644 --- a/tests/static-styles.test.mjs +++ b/tests/static-styles.test.mjs @@ -109,7 +109,8 @@ test("large sass files stay split by stable responsibility", async () => { "website/src/styles/toolboxes/calendar/_form-layout.scss", "website/src/styles/toolboxes/calendar/_date-picker.scss", "website/src/styles/toolboxes/calendar/_event-controls.scss", - "website/src/styles/toolboxes/calendar/_form-actions.scss" + "website/src/styles/toolboxes/calendar/_form-actions.scss", + "website/src/styles/_nebula-expeditions.scss" ]; for (const path of orchestrators) { diff --git a/website/public/data/cards/catalog.json b/website/public/data/cards/catalog.json index 0563530..c32a6c4 100644 --- a/website/public/data/cards/catalog.json +++ b/website/public/data/cards/catalog.json @@ -311,6 +311,284 @@ "highlight": "#ddd6fe" } ], + "expeditionTags": [ + { + "id": "personnage:dragon", + "label": "Dragon" + }, + { + "id": "personnage:kitsune", + "label": "Kitsune" + }, + { + "id": "personnage:panda", + "label": "Panda" + }, + { + "id": "personnage:pie", + "label": "Pie" + }, + { + "id": "personnage:capybara", + "label": "Capybara" + }, + { + "id": "personnage:loup", + "label": "Loup" + }, + { + "id": "personnage:renard", + "label": "Renardeau" + }, + { + "id": "personnage:hibou", + "label": "Hibou et chouette" + }, + { + "id": "personnage:lynx", + "label": "Lynx" + }, + { + "id": "personnage:panthere", + "label": "Panthère" + }, + { + "id": "personnage:salamandre", + "label": "Salamandre" + }, + { + "id": "personnage:cerf", + "label": "Cerf et faon" + }, + { + "id": "personnage:fennec", + "label": "Fennec" + }, + { + "id": "personnage:axolotl", + "label": "Axolotl" + }, + { + "id": "personnage:herisson", + "label": "Hérisson" + }, + { + "id": "personnage:cameleon", + "label": "Caméléon" + }, + { + "id": "personnage:chauve-souris", + "label": "Chauve-souris" + }, + { + "id": "personnage:ecureuil", + "label": "Écureuil" + }, + { + "id": "personnage:raton-laveur", + "label": "Raton laveur" + }, + { + "id": "personnage:grenouille", + "label": "Grenouille et rainette" + }, + { + "id": "personnage:gecko", + "label": "Gecko" + }, + { + "id": "personnage:suricate", + "label": "Suricate" + }, + { + "id": "personnage:furet", + "label": "Furet" + }, + { + "id": "personnage:ornithorynque", + "label": "Ornithorynque" + }, + { + "id": "personnage:alpaga", + "label": "Alpaga" + }, + { + "id": "personnage:koala", + "label": "Koala" + }, + { + "id": "personnage:caneton", + "label": "Caneton" + }, + { + "id": "personnage:loir", + "label": "Loir" + }, + { + "id": "personnage:manchot", + "label": "Manchot" + }, + { + "id": "personnage:panda-roux", + "label": "Panda roux" + }, + { + "id": "personnage:rouge-gorge", + "label": "Rouge-gorge" + }, + { + "id": "personnage:chinchilla", + "label": "Chinchilla" + }, + { + "id": "personnage:hamster", + "label": "Hamster" + }, + { + "id": "personnage:loutre", + "label": "Loutre" + }, + { + "id": "personnage:ours", + "label": "Ours" + }, + { + "id": "lieu:nebuleuse", + "label": "La Nébuleuse" + }, + { + "id": "lieu:soleil", + "label": "Le Soleil et l'aube" + }, + { + "id": "lieu:lune-ecarlate", + "label": "La Lune Écarlate" + }, + { + "id": "lieu:lune-pale", + "label": "La Lune Pâle" + }, + { + "id": "lieu:vide", + "label": "Le vide" + }, + { + "id": "lieu:courants", + "label": "Les courants de lumière" + }, + { + "id": "lieu:glaces", + "label": "Les îles de glace" + }, + { + "id": "lieu:observatoire", + "label": "Les observatoires" + }, + { + "id": "lieu:iles-jeux", + "label": "Les îles-jeux" + }, + { + "id": "theme:veilleurs", + "label": "Veilleurs" + }, + { + "id": "theme:voyage", + "label": "Voyage" + }, + { + "id": "theme:reves", + "label": "Rêves" + }, + { + "id": "theme:hiver", + "label": "Hiver" + }, + { + "id": "theme:fete", + "label": "Fête" + }, + { + "id": "theme:nuit", + "label": "Nuit" + }, + { + "id": "theme:constellations", + "label": "Constellations" + }, + { + "id": "theme:cometes", + "label": "Comètes et météores" + }, + { + "id": "theme:eau", + "label": "Eau" + }, + { + "id": "theme:aurores", + "label": "Aurores" + }, + { + "id": "theme:passages", + "label": "Passages secrets" + }, + { + "id": "theme:aventure", + "label": "Aventure" + }, + { + "id": "theme:tresor", + "label": "Trésor" + }, + { + "id": "theme:jardin", + "label": "Jardins et récoltes" + }, + { + "id": "theme:poussiere", + "label": "Poussière d'étoiles" + }, + { + "id": "theme:collection", + "label": "Collectionneurs" + }, + { + "id": "objet:lunette", + "label": "Lunette" + }, + { + "id": "objet:boussole", + "label": "Boussole et astrolabe" + }, + { + "id": "objet:carte", + "label": "Carte" + }, + { + "id": "objet:lanterne", + "label": "Lanterne" + }, + { + "id": "objet:ecriture", + "label": "Plume, encre et carnet" + }, + { + "id": "objet:pierre", + "label": "Pierre et éclat" + }, + { + "id": "objet:cristal", + "label": "Cristal" + }, + { + "id": "objet:cadeau", + "label": "Cadeau" + }, + { + "id": "objet:arme", + "label": "Épée" + } + ], "collections": [ { "id": "primordial-nebula", @@ -325,7 +603,15 @@ "secondary": "#312e81", "symbol": "star" }, - "dropTableVersion": 1 + "dropTableVersion": 1, + "expedition": { + "profile": { + "bravoure": 25, + "endurance": 25, + "fortune": 20, + "orientation": 30 + } + } }, { "id": "astral-genesis", @@ -340,7 +626,15 @@ "secondary": "#b7791f", "symbol": "orbit" }, - "dropTableVersion": 1 + "dropTableVersion": 1, + "expedition": { + "profile": { + "bravoure": 20, + "endurance": 20, + "fortune": 40, + "orientation": 20 + } + } }, { "id": "stardust", @@ -355,7 +649,15 @@ "secondary": "#b7791f", "symbol": "orbit" }, - "dropTableVersion": 1 + "dropTableVersion": 1, + "expedition": { + "profile": { + "bravoure": 25, + "endurance": 25, + "fortune": 30, + "orientation": 20 + } + } }, { "id": "long-night", @@ -370,7 +672,15 @@ "secondary": "#b7791f", "symbol": "star" }, - "dropTableVersion": 1 + "dropTableVersion": 1, + "expedition": { + "profile": { + "bravoure": 20, + "endurance": 40, + "fortune": 25, + "orientation": 15 + } + } }, { "id": "dream-arcade", @@ -385,7 +695,15 @@ "secondary": "#b7791f", "symbol": "star" }, - "dropTableVersion": 1 + "dropTableVersion": 1, + "expedition": { + "profile": { + "bravoure": 35, + "endurance": 20, + "fortune": 30, + "orientation": 15 + } + } } ], "cards": [ @@ -395,7 +713,20 @@ "name": "Dragon du Néant Étoilé", "description": "Au début, le Dragon s'enroula autour de la Nébuleuse et la serra si fort qu'elle s'effondra. Le Soleil s'alluma au centre et le reste se brisa en îles.", "image": "/static/img/cards/primordial-nebula/legendary/starvoid_dragon.webp", - "fullImage": "/static/img/cards/primordial-nebula/legendary/starvoid_dragon__full.webp" + "fullImage": "/static/img/cards/primordial-nebula/legendary/starvoid_dragon__full.webp", + "expedition": { + "tags": [ + "personnage:dragon", + "lieu:nebuleuse", + "lieu:soleil" + ], + "profile": { + "bravoure": 40, + "endurance": 30, + "fortune": 15, + "orientation": 15 + } + } }, { "id": "crimson-moon-kitsune", @@ -403,7 +734,20 @@ "name": "Kitsune de la Lune Écarlate", "description": "La Lune Écarlate est née du choc de deux îles. Les nuits où elle brille, son renard ouvre des passages secrets entre des îles très éloignées.", "image": "/static/img/cards/primordial-nebula/legendary/crimson_moon_kitsune.webp", - "fullImage": "/static/img/cards/primordial-nebula/legendary/crimson_moon_kitsune__full.webp" + "fullImage": "/static/img/cards/primordial-nebula/legendary/crimson_moon_kitsune__full.webp", + "expedition": { + "tags": [ + "personnage:kitsune", + "lieu:lune-ecarlate", + "theme:passages" + ], + "profile": { + "bravoure": 20, + "endurance": 15, + "fortune": 25, + "orientation": 40 + } + } }, { "id": "milky-way-panda", @@ -411,7 +755,20 @@ "name": "Panda de la Voie Lactée", "description": "Le Panda dort dans la longue bande d'étoiles laissée par la Nébuleuse. Ses rêves y rassemblent la poussière, et chaque nouvelle île serait l'un d'eux.", "image": "/static/img/cards/primordial-nebula/legendary/milky_way_panda.webp", - "fullImage": "/static/img/cards/primordial-nebula/legendary/milky_way_panda__full.webp" + "fullImage": "/static/img/cards/primordial-nebula/legendary/milky_way_panda__full.webp", + "expedition": { + "tags": [ + "personnage:panda", + "theme:reves", + "theme:poussiere" + ], + "profile": { + "bravoure": 15, + "endurance": 25, + "fortune": 40, + "orientation": 20 + } + } }, { "id": "constellation-magpie", @@ -419,7 +776,20 @@ "name": "Pie des Constellations", "description": "Les étoiles sœurs sont nées ensemble, puis se sont éloignées. La Pie relie celles qu'elle retrouve : ce sont les constellations qui guident les voyageurs.", "image": "/static/img/cards/primordial-nebula/legendary/constellation_magpie.webp", - "fullImage": "/static/img/cards/primordial-nebula/legendary/constellation_magpie__full.webp" + "fullImage": "/static/img/cards/primordial-nebula/legendary/constellation_magpie__full.webp", + "expedition": { + "tags": [ + "personnage:pie", + "theme:constellations", + "theme:voyage" + ], + "profile": { + "bravoure": 15, + "endurance": 15, + "fortune": 30, + "orientation": 40 + } + } }, { "id": "solar-dawn-capybara", @@ -427,7 +797,19 @@ "name": "Capybara de l'Aube Solaire", "description": "Quand le Soleil s'est allumé, le Capybara s'est installé dans sa lumière. Tant qu'il reste calme, le Soleil brille et réchauffe toutes les îles.", "image": "/static/img/cards/primordial-nebula/legendary/solar_dawn_capybara.webp", - "fullImage": "/static/img/cards/primordial-nebula/legendary/solar_dawn_capybara__full.webp" + "fullImage": "/static/img/cards/primordial-nebula/legendary/solar_dawn_capybara__full.webp", + "expedition": { + "tags": [ + "personnage:capybara", + "lieu:soleil" + ], + "profile": { + "bravoure": 20, + "endurance": 45, + "fortune": 20, + "orientation": 15 + } + } }, { "id": "aurora-wolf", @@ -435,539 +817,1099 @@ "name": "Loup des Aurores", "description": "Le Soleil souffle un vent brûlant sur les îles. Le Loup le repousse en hurlant, et les aurores qui colorent alors le ciel sont la trace de ce combat.", "image": "/static/img/cards/primordial-nebula/legendary/aurora_wolf.webp", - "fullImage": "/static/img/cards/primordial-nebula/legendary/aurora_wolf__full.webp" + "fullImage": "/static/img/cards/primordial-nebula/legendary/aurora_wolf__full.webp", + "expedition": { + "tags": [ + "personnage:loup", + "theme:aurores", + "lieu:soleil" + ], + "profile": { + "bravoure": 40, + "endurance": 35, + "fortune": 10, + "orientation": 15 + } + } }, { "id": "astral-crescent-howl", "collectionId": "primordial-nebula", "name": "Hurlement du Croissant Astral", "description": "Les nuits de croissant de lune, le hurlement du Loup traverse le vide d'île en île. Les îles les plus isolées savent alors qu'elles ne sont pas seules.", - "image": "/static/img/cards/primordial-nebula/epic/astral_crescent_howl.webp" + "image": "/static/img/cards/primordial-nebula/epic/astral_crescent_howl.webp", + "expedition": { + "tags": [ + "personnage:loup", + "theme:nuit", + "lieu:vide" + ] + } }, { "id": "eclipse-lynx", "collectionId": "primordial-nebula", "name": "Lynx de l'Éclipse", "description": "Quand une île passe devant le Soleil, son ombre glisse sur les îles voisines. Le lynx court dans cette ombre et disparaît dès que la lumière revient.", - "image": "/static/img/cards/primordial-nebula/epic/eclipse_lynx.webp" + "image": "/static/img/cards/primordial-nebula/epic/eclipse_lynx.webp", + "expedition": { + "tags": [ + "personnage:lynx", + "lieu:soleil" + ] + } }, { "id": "silent-star-owl", "collectionId": "primordial-nebula", "name": "Hibou des Étoiles Silencieuses", "description": "Il a vu s'éteindre des étoiles sœurs que la Pie ne retrouvera jamais. Il connaît encore leurs noms, mais les garde pour lui comme un précieux secret.", - "image": "/static/img/cards/primordial-nebula/epic/silent_star_owl.webp" + "image": "/static/img/cards/primordial-nebula/epic/silent_star_owl.webp", + "expedition": { + "tags": [ + "personnage:hibou", + "theme:constellations", + "theme:nuit" + ] + } }, { "id": "night-veil-bat", "collectionId": "primordial-nebula", "name": "Chauve-souris du Voile Nocturne", "description": "Au fond des grottes, elle entend un grondement venu du cœur des îles. Pour les Veilleurs, c'est le dernier écho du jour où la Nébuleuse s'est effondrée.", - "image": "/static/img/cards/primordial-nebula/epic/night_veil_bat.webp" + "image": "/static/img/cards/primordial-nebula/epic/night_veil_bat.webp", + "expedition": { + "tags": [ + "personnage:chauve-souris", + "theme:veilleurs", + "theme:nuit", + "lieu:nebuleuse" + ] + } }, { "id": "celestial-shadow-panther", "collectionId": "primordial-nebula", "name": "Panthère des Ombres Célestes", "description": "Elle rôde dans le vide entre les îles, là où il fait le plus noir. Ses yeux argentés montrent le chemin du retour aux bateaux du ciel égarés.", - "image": "/static/img/cards/primordial-nebula/epic/celestial_shadow_panther.webp" + "image": "/static/img/cards/primordial-nebula/epic/celestial_shadow_panther.webp", + "expedition": { + "tags": [ + "personnage:panthere", + "lieu:vide", + "theme:voyage" + ], + "profile": { + "bravoure": 35, + "endurance": 15, + "fortune": 10, + "orientation": 40 + } + } }, { "id": "dawn-antler-deer", "collectionId": "primordial-nebula", "name": "Cerf aux Bois d'Aurore", "description": "Sur les îles tournées vers le Soleil, ses bois brillent dès les premières lueurs. Quand on les voit s'allumer, on sait que les beaux jours reviennent.", - "image": "/static/img/cards/primordial-nebula/epic/dawn_antler_deer.webp" + "image": "/static/img/cards/primordial-nebula/epic/dawn_antler_deer.webp", + "expedition": { + "tags": [ + "personnage:cerf", + "lieu:soleil" + ] + } }, { "id": "solar-dust-butterfly", "collectionId": "primordial-nebula", "name": "Papillon des Poussières Solaires", "description": "Ses ailes répandent la poussière dorée laissée par le Soleil. Là où elle tombe, même la roche nue des jeunes îles finit par se couvrir de fleurs.", - "image": "/static/img/cards/primordial-nebula/epic/solar_dust_butterfly.webp" + "image": "/static/img/cards/primordial-nebula/epic/solar_dust_butterfly.webp", + "expedition": { + "tags": [ + "lieu:soleil", + "theme:poussiere", + "theme:jardin" + ] + } }, { "id": "starlit-sand-fennec", "collectionId": "primordial-nebula", "name": "Fennec des Sables Stellaires", "description": "Le sable de ses dunes est la poussière de la Nébuleuse, aussi fine qu'au premier jour. Ses traces mènent parfois vers des îles que personne n'a vues.", - "image": "/static/img/cards/primordial-nebula/epic/starlit_sand_fennec.webp" + "image": "/static/img/cards/primordial-nebula/epic/starlit_sand_fennec.webp", + "expedition": { + "tags": [ + "personnage:fennec", + "theme:poussiere", + "lieu:nebuleuse", + "theme:voyage" + ] + } }, { "id": "rose-dawn-hummingbird", "collectionId": "primordial-nebula", "name": "Colibri de l'Aube Rose", "description": "Il butine avant même que le Soleil n'éclaire son île, puis file vers la suivante. En portant le pollen d'île en île, il relie tous les jardins du ciel.", - "image": "/static/img/cards/primordial-nebula/epic/rose_dawn_hummingbird.webp" + "image": "/static/img/cards/primordial-nebula/epic/rose_dawn_hummingbird.webp", + "expedition": { + "tags": [ + "lieu:soleil", + "theme:jardin", + "theme:voyage" + ] + } }, { "id": "astral-ember-salamander", "collectionId": "primordial-nebula", "name": "Salamandre des Braises Astrales", "description": "Elle sent les météorites avant leur chute et court vers les cratères encore brûlants. C'est en la suivant qu'on a trouvé l'Écaille du Néant.", - "image": "/static/img/cards/primordial-nebula/epic/astral_ember_salamander.webp" + "image": "/static/img/cards/primordial-nebula/epic/astral_ember_salamander.webp", + "expedition": { + "tags": [ + "personnage:salamandre", + "theme:cometes", + "theme:veilleurs" + ] + } }, { "id": "orbital-ring-turtle", "collectionId": "primordial-nebula", "name": "Tortue aux Anneaux Orbitaux", "description": "Son anneau tourne comme tournait la Nébuleuse avant de se briser en îles. Les Veilleurs l'observent pour comprendre comment leur monde est né.", - "image": "/static/img/cards/primordial-nebula/epic/orbital_ring_turtle.webp" + "image": "/static/img/cards/primordial-nebula/epic/orbital_ring_turtle.webp", + "expedition": { + "tags": [ + "theme:veilleurs", + "lieu:nebuleuse" + ] + } }, { "id": "cosmic-water-axolotl", "collectionId": "primordial-nebula", "name": "Axolotl des Eaux Cosmiques", "description": "Toute l'eau des îles est arrivée avec les comètes. L'axolotl vit dans les lacs les plus anciens, et il se souviendrait encore de ce long voyage.", - "image": "/static/img/cards/primordial-nebula/epic/cosmic_water_axolotl.webp" + "image": "/static/img/cards/primordial-nebula/epic/cosmic_water_axolotl.webp", + "expedition": { + "tags": [ + "personnage:axolotl", + "theme:eau", + "theme:cometes" + ] + } }, { "id": "astral-prism-chameleon", "collectionId": "primordial-nebula", "name": "Caméléon du Prisme Astral", "description": "Ses couleurs changent quand il touche les cristaux nés dans la Nébuleuse. Certaines de ces couleurs n'existent nulle part ailleurs dans les îles.", - "image": "/static/img/cards/primordial-nebula/epic/astral_prism_chameleon.webp" + "image": "/static/img/cards/primordial-nebula/epic/astral_prism_chameleon.webp", + "expedition": { + "tags": [ + "personnage:cameleon", + "lieu:nebuleuse", + "objet:cristal" + ] + } }, { "id": "stellar-current-otter", "collectionId": "primordial-nebula", "name": "Loutre des Courants Stellaires", "description": "Des courants de lumière relient les îles entre elles. La loutre s'y laisse porter en jouant, et c'est en la suivant qu'on a appris à voyager.", - "image": "/static/img/cards/primordial-nebula/epic/stellar_current_otter.webp" + "image": "/static/img/cards/primordial-nebula/epic/stellar_current_otter.webp", + "expedition": { + "tags": [ + "personnage:loutre", + "lieu:courants", + "theme:voyage" + ], + "profile": { + "bravoure": 20, + "endurance": 20, + "fortune": 20, + "orientation": 40 + } + } }, { "id": "moonrain-frog", "collectionId": "primordial-nebula", "name": "Grenouille de la Pluie Lunaire", "description": "Quand la Lune Écarlate a refroidi, une pluie argentée est tombée sur les îles. Le chant de cette grenouille la rappelle et annonce une saison douce.", - "image": "/static/img/cards/primordial-nebula/epic/moonrain_frog.webp" + "image": "/static/img/cards/primordial-nebula/epic/moonrain_frog.webp", + "expedition": { + "tags": [ + "personnage:grenouille", + "lieu:lune-ecarlate", + "theme:eau" + ] + } }, { "id": "nebula-mist-jellyfish", "collectionId": "primordial-nebula", "name": "Méduse des Brumes Nébuleuses", "description": "Elle flotte dans les dernières brumes de la Nébuleuse, au bord du monde. On dit qu'une nouvelle île finit toujours par naître là où elle passe.", - "image": "/static/img/cards/primordial-nebula/epic/nebula_mist_jellyfish.webp" + "image": "/static/img/cards/primordial-nebula/epic/nebula_mist_jellyfish.webp", + "expedition": { + "tags": [ + "lieu:nebuleuse", + "lieu:vide" + ] + } }, { "id": "comet-squirrel", "collectionId": "primordial-nebula", "name": "Écureuil des Comètes", "description": "Il saute de comète en comète pour y cacher ses provisions. À chaque retour d'une comète, il retrouve ses réserves, et les îles reçoivent un peu d'eau.", - "image": "/static/img/cards/primordial-nebula/epic/comet_squirrel.webp" + "image": "/static/img/cards/primordial-nebula/epic/comet_squirrel.webp", + "expedition": { + "tags": [ + "personnage:ecureuil", + "theme:cometes", + "theme:eau" + ] + } }, { "id": "deep-sky-ray", "collectionId": "primordial-nebula", "name": "Raie des Cieux Profonds", "description": "Elle nage dans le vide comme un poisson dans l'océan. Les bateaux du ciel qui la croisent ralentissent, et on a l'impression que le temps s'arrête.", - "image": "/static/img/cards/primordial-nebula/epic/deep_sky_ray.webp" + "image": "/static/img/cards/primordial-nebula/epic/deep_sky_ray.webp", + "expedition": { + "tags": [ + "lieu:vide", + "theme:voyage" + ] + } }, { "id": "star-spined-hedgehog", "collectionId": "primordial-nebula", "name": "Hérisson aux Épines d'Étoiles", "description": "Ses épines brillent des étincelles tombées des ailes du Dragon. Roulé en boule, il ressemble au ciel des premiers jours, que plus aucune carte ne montre.", - "image": "/static/img/cards/primordial-nebula/epic/star_spined_hedgehog.webp" + "image": "/static/img/cards/primordial-nebula/epic/star_spined_hedgehog.webp", + "expedition": { + "tags": [ + "personnage:herisson", + "theme:constellations" + ] + } }, { "id": "lunar-cloud-rabbit", "collectionId": "primordial-nebula", "name": "Lapin des Nuages Lunaires", "description": "Les soirs de pleine lune, ce lapin saute de nuage en nuage entre les îles. Le matin, les formes laissées dans la brume montrent le chemin le plus sûr.", - "image": "/static/img/cards/primordial-nebula/epic/lunar_cloud_rabbit.webp" + "image": "/static/img/cards/primordial-nebula/epic/lunar_cloud_rabbit.webp", + "expedition": { + "tags": [ + "theme:voyage", + "theme:nuit" + ] + } }, { "id": "twilight-red-panda", "collectionId": "primordial-nebula", "name": "Panda Roux du Crépuscule", "description": "Chaque soir, il dort sur la même pierre, au bord du vide. Les habitants de son île disent qu'il veille pour qu'elle ne s'éloigne pas pendant la nuit.", - "image": "/static/img/cards/primordial-nebula/rare/twilight_red_panda.webp" + "image": "/static/img/cards/primordial-nebula/rare/twilight_red_panda.webp", + "expedition": { + "tags": [ + "personnage:panda-roux", + "lieu:vide", + "theme:nuit" + ] + } }, { "id": "pale-moon-owl", "collectionId": "primordial-nebula", "name": "Chouette de la Lune Pâle", "description": "Quand la Lune Pâle se cache, elle guide les voyageurs en retard jusqu'à chez eux. Les Veilleurs l'ont choisie comme emblème de leurs observatoires.", - "image": "/static/img/cards/primordial-nebula/rare/pale_moon_owl.webp" + "image": "/static/img/cards/primordial-nebula/rare/pale_moon_owl.webp", + "expedition": { + "tags": [ + "personnage:hibou", + "lieu:lune-pale", + "theme:veilleurs", + "theme:voyage" + ], + "profile": { + "bravoure": 15, + "endurance": 20, + "fortune": 15, + "orientation": 50 + } + } }, { "id": "night-reflection-raccoon", "collectionId": "primordial-nebula", "name": "Raton Laveur des Reflets Nocturnes", "description": "Il essaie d'attraper les étoiles qui se reflètent dans les flaques. Il n'y arrive jamais, mais il en ressort souvent de petits morceaux de météorite.", - "image": "/static/img/cards/primordial-nebula/rare/night_reflection_raccoon.webp" + "image": "/static/img/cards/primordial-nebula/rare/night_reflection_raccoon.webp", + "expedition": { + "tags": [ + "personnage:raton-laveur", + "theme:cometes", + "theme:nuit" + ] + } }, { "id": "astral-snow-fox-cub", "collectionId": "primordial-nebula", "name": "Renardeau des Neiges Astrales", "description": "Ses empreintes traversent les îles enneigées, puis s'arrêtent net au bord du vide. Il connaîtrait l'un des passages secrets ouverts par le Kitsune.", - "image": "/static/img/cards/primordial-nebula/rare/astral_snow_fox_cub.webp" + "image": "/static/img/cards/primordial-nebula/rare/astral_snow_fox_cub.webp", + "expedition": { + "tags": [ + "personnage:renard", + "lieu:glaces", + "theme:passages", + "theme:hiver" + ] + } }, { "id": "starry-dream-dormouse", "collectionId": "primordial-nebula", "name": "Loir des Songes Étoilés", "description": "Il dort des semaines dans son tronc creux, comme le Panda parmi les étoiles. Pendant ce temps, les lucioles de son île veillent sur ses rêves.", - "image": "/static/img/cards/primordial-nebula/rare/starry_dream_dormouse.webp" + "image": "/static/img/cards/primordial-nebula/rare/starry_dream_dormouse.webp", + "expedition": { + "tags": [ + "personnage:loir", + "theme:reves" + ] + } }, { "id": "first-light-duckling", "collectionId": "primordial-nebula", "name": "Caneton des Premières Lueurs", "description": "Il traverse la prairie au lever du jour, avant tout le monde. Sur les îles de l'aube, ses traces dans la rosée passent pour un cadeau du Capybara.", - "image": "/static/img/cards/primordial-nebula/rare/first_light_duckling.webp" + "image": "/static/img/cards/primordial-nebula/rare/first_light_duckling.webp", + "expedition": { + "tags": [ + "personnage:caneton", + "lieu:soleil" + ] + } }, { "id": "solar-seed-hamster", "collectionId": "primordial-nebula", "name": "Hamster aux Graines Solaires", "description": "Il ramasse les graines dorées qui poussent là où le Papillon est passé. Celles qu'il oublie suffisent parfois à faire fleurir une île entière.", - "image": "/static/img/cards/primordial-nebula/rare/solar_seed_hamster.webp" + "image": "/static/img/cards/primordial-nebula/rare/solar_seed_hamster.webp", + "expedition": { + "tags": [ + "personnage:hamster", + "lieu:soleil", + "theme:jardin" + ] + } }, { "id": "golden-dew-fawn", "collectionId": "primordial-nebula", "name": "Faon de la Rosée Dorée", "description": "Le matin, ce faon suit les traces du Cerf aux Bois d'Aurore jusqu'aux mares de son île. Le croiser promettait une journée sans pluie de météores.", - "image": "/static/img/cards/primordial-nebula/rare/golden_dew_fawn.webp" + "image": "/static/img/cards/primordial-nebula/rare/golden_dew_fawn.webp", + "expedition": { + "tags": [ + "personnage:cerf", + "lieu:soleil", + "theme:cometes" + ] + } }, { "id": "amber-dune-meerkat", "collectionId": "primordial-nebula", "name": "Suricate des Dunes d'Ambre", "description": "Debout en haut des dunes, il surveille le ciel et crie quand des météores approchent. Sur son île, tout le monde s'abrite avant même de les voir.", - "image": "/static/img/cards/primordial-nebula/rare/amber_dune_meerkat.webp" + "image": "/static/img/cards/primordial-nebula/rare/amber_dune_meerkat.webp", + "expedition": { + "tags": [ + "personnage:suricate", + "theme:cometes" + ], + "profile": { + "bravoure": 20, + "endurance": 35, + "fortune": 15, + "orientation": 30 + } + } }, { "id": "pink-horizon-robin", "collectionId": "primordial-nebula", "name": "Rouge-gorge de l'Horizon Rose", "description": "Il chante quand le ciel devient rose au-dessus des îles. Ceux qui partent pour un long voyage attendent toujours son chant avant de s'en aller.", - "image": "/static/img/cards/primordial-nebula/rare/pink_horizon_robin.webp" + "image": "/static/img/cards/primordial-nebula/rare/pink_horizon_robin.webp", + "expedition": { + "tags": [ + "personnage:rouge-gorge", + "theme:voyage", + "lieu:soleil" + ] + } }, { "id": "celestial-stream-platypus", "collectionId": "primordial-nebula", "name": "Ornithorynque des Ruisseaux Célestes", "description": "Il fouille les ruisseaux qui tombent dans le vide au bord de son île. Il en ramène des pierres aux reflets argentés, arrivées avec les comètes.", - "image": "/static/img/cards/primordial-nebula/rare/celestial_stream_platypus.webp" + "image": "/static/img/cards/primordial-nebula/rare/celestial_stream_platypus.webp", + "expedition": { + "tags": [ + "personnage:ornithorynque", + "theme:eau", + "theme:cometes", + "lieu:vide" + ] + } }, { "id": "azure-stone-gecko", "collectionId": "primordial-nebula", "name": "Gecko des Pierres Azurées", "description": "Il adore les roches bleues tombées de la Lune Pâle. Les mineurs le suivaient pour trouver le métal qui sert à fabriquer les outils des Veilleurs.", - "image": "/static/img/cards/primordial-nebula/rare/azure_stone_gecko.webp" + "image": "/static/img/cards/primordial-nebula/rare/azure_stone_gecko.webp", + "expedition": { + "tags": [ + "personnage:gecko", + "lieu:lune-pale", + "theme:veilleurs" + ] + } }, { "id": "celestial-mirror-kingfisher", "collectionId": "primordial-nebula", "name": "Martin-pêcheur du Miroir Céleste", "description": "Il plonge dans des lacs si calmes qu'ils reflètent tout le ciel. Dès que l'eau redevient lisse, les Veilleurs y notent la place des étoiles.", - "image": "/static/img/cards/primordial-nebula/rare/celestial_mirror_kingfisher.webp" + "image": "/static/img/cards/primordial-nebula/rare/celestial_mirror_kingfisher.webp", + "expedition": { + "tags": [ + "theme:eau", + "theme:veilleurs", + "theme:constellations" + ] + } }, { "id": "mist-pearl-tree-frog", "collectionId": "primordial-nebula", "name": "Rainette des Perles de Brume", "description": "Elle s'installe sur les pierres couvertes de rosée quand une comète approche. Son chant prévenait les paysans que l'eau allait bientôt arriver.", - "image": "/static/img/cards/primordial-nebula/rare/mist_pearl_tree_frog.webp" + "image": "/static/img/cards/primordial-nebula/rare/mist_pearl_tree_frog.webp", + "expedition": { + "tags": [ + "personnage:grenouille", + "theme:eau", + "theme:cometes" + ] + } }, { "id": "moon-shell-otter-pup", "collectionId": "primordial-nebula", "name": "Loutron des Coquillages Lunaires", "description": "Ce loutron ramasse les coquillages brillants des lacs nés de la pluie lunaire. Il les garde un moment, puis les offre à ses amis de la rivière.", - "image": "/static/img/cards/primordial-nebula/rare/moon_shell_otter_pup.webp" + "image": "/static/img/cards/primordial-nebula/rare/moon_shell_otter_pup.webp", + "expedition": { + "tags": [ + "personnage:loutre", + "theme:eau", + "lieu:lune-ecarlate" + ] + } }, { "id": "lunar-mist-chinchilla", "collectionId": "primordial-nebula", "name": "Chinchilla des Brumes Lunaires", "description": "Il se repose sur les pierres encore chaudes quand le Soleil se couche. Quand la brume monte du vide, son pelage argenté le rend presque invisible.", - "image": "/static/img/cards/primordial-nebula/rare/lunar_mist_chinchilla.webp" + "image": "/static/img/cards/primordial-nebula/rare/lunar_mist_chinchilla.webp", + "expedition": { + "tags": [ + "personnage:chinchilla", + "lieu:soleil", + "lieu:vide" + ] + } }, { "id": "starlit-ice-penguin", "collectionId": "primordial-nebula", "name": "Manchot des Glaces Étoilées", "description": "Sur les îles de glace les plus loin du Soleil, il adore glisser le long des pentes. Ses amis le suivent, et la colline devient un grand toboggan.", - "image": "/static/img/cards/primordial-nebula/rare/starlit_ice_penguin.webp" + "image": "/static/img/cards/primordial-nebula/rare/starlit_ice_penguin.webp", + "expedition": { + "tags": [ + "personnage:manchot", + "lieu:glaces", + "theme:hiver" + ] + } }, { "id": "lavender-sky-koala", "collectionId": "primordial-nebula", "name": "Koala du Ciel Lavande", "description": "Depuis sa colline, il regarde passer les îles voisines dans le ciel lavande. Les étoiles filantes semblent plus nombreuses quand il est réveillé.", - "image": "/static/img/cards/primordial-nebula/rare/lavender_sky_koala.webp" + "image": "/static/img/cards/primordial-nebula/rare/lavender_sky_koala.webp", + "expedition": { + "tags": [ + "personnage:koala", + "theme:reves", + "theme:nuit" + ] + } }, { "id": "stellar-wind-ferret", "collectionId": "primordial-nebula", "name": "Furet des Vents Stellaires", "description": "Il court dans les prairies dès que souffle le vent du Soleil, celui que le Loup retient au-dessus des îles. Sa vitesse a inspiré bien des histoires.", - "image": "/static/img/cards/primordial-nebula/rare/stellar_wind_ferret.webp" + "image": "/static/img/cards/primordial-nebula/rare/stellar_wind_ferret.webp", + "expedition": { + "tags": [ + "personnage:furet", + "lieu:soleil" + ] + } }, { "id": "opaline-cloud-alpaca", "collectionId": "primordial-nebula", "name": "Alpaga des Nuages Opalins", "description": "Il traverse sans peur les ponts de nuages qui relient deux îles. Quand la brume cache les chemins, les bergers savent qu'ils peuvent le suivre.", - "image": "/static/img/cards/primordial-nebula/rare/opaline_cloud_alpaca.webp" + "image": "/static/img/cards/primordial-nebula/rare/opaline_cloud_alpaca.webp", + "expedition": { + "tags": [ + "personnage:alpaga", + "theme:voyage" + ], + "profile": { + "bravoure": 15, + "endurance": 30, + "fortune": 15, + "orientation": 40 + } + } }, { "id": "dragon-constellation", "collectionId": "primordial-nebula", "name": "Constellation du Dragon", "description": "C'est la première constellation dessinée par les Veilleurs. Ses étoiles forment les anneaux du Dragon, serrés comme au jour où tout a commencé.", - "image": "/static/img/cards/primordial-nebula/common/dragon_constellation.webp" + "image": "/static/img/cards/primordial-nebula/common/dragon_constellation.webp", + "expedition": { + "tags": [ + "theme:constellations", + "theme:veilleurs", + "personnage:dragon" + ] + } }, { "id": "wolf-constellation", "collectionId": "primordial-nebula", "name": "Constellation du Loup", "description": "Elle apparaît quand les aurores sont les plus belles. Les Veilleurs y voient le Loup qui monte la garde, tourné vers le Soleil pour protéger les îles.", - "image": "/static/img/cards/primordial-nebula/common/wolf_constellation.webp" + "image": "/static/img/cards/primordial-nebula/common/wolf_constellation.webp", + "expedition": { + "tags": [ + "theme:constellations", + "personnage:loup", + "theme:aurores" + ] + } }, { "id": "fox-constellation", "collectionId": "primordial-nebula", "name": "Constellation du Renard", "description": "Ses étoiles semblent bouger les nuits de Lune Écarlate. Les Veilleurs pensent qu'elles montrent alors où s'ouvrent les passages du Kitsune.", - "image": "/static/img/cards/primordial-nebula/common/fox_constellation.webp" + "image": "/static/img/cards/primordial-nebula/common/fox_constellation.webp", + "expedition": { + "tags": [ + "theme:constellations", + "personnage:kitsune", + "lieu:lune-ecarlate", + "theme:passages" + ] + } }, { "id": "panda-constellation", "collectionId": "primordial-nebula", "name": "Constellation du Panda", "description": "Elle s'étend sur la bande d'étoiles où dort le Panda. Dans les îles, on la cherche des yeux avant de s'endormir, pour faire de beaux rêves.", - "image": "/static/img/cards/primordial-nebula/common/panda_constellation.webp" + "image": "/static/img/cards/primordial-nebula/common/panda_constellation.webp", + "expedition": { + "tags": [ + "theme:constellations", + "personnage:panda", + "theme:reves" + ] + } }, { "id": "capybara-constellation", "collectionId": "primordial-nebula", "name": "Constellation du Capybara", "description": "On la voit juste avant le lever du jour, du côté du Soleil. Les voyageurs la suivent pour atteindre les îles de l'aube avant que le matin arrive.", - "image": "/static/img/cards/primordial-nebula/common/capybara_constellation.webp" + "image": "/static/img/cards/primordial-nebula/common/capybara_constellation.webp", + "expedition": { + "tags": [ + "theme:constellations", + "personnage:capybara", + "lieu:soleil", + "theme:voyage" + ] + } }, { "id": "magpie-constellation", "collectionId": "primordial-nebula", "name": "Constellation de la Pie", "description": "Une nouvelle étoile apparaît parfois près de son bec. Pour les Veilleurs, cela veut dire que la Pie vient de retrouver l'une des étoiles sœurs.", - "image": "/static/img/cards/primordial-nebula/common/magpie_constellation.webp" + "image": "/static/img/cards/primordial-nebula/common/magpie_constellation.webp", + "expedition": { + "tags": [ + "theme:constellations", + "personnage:pie" + ] + } }, { "id": "void-scale", "collectionId": "primordial-nebula", "name": "Écaille du Néant", "description": "Tombée dans un cratère, elle a été trouvée grâce à la Salamandre. Le premier observatoire a été construit autour d'elle : les Veilleurs sont nés là.", - "image": "/static/img/cards/primordial-nebula/common/void_scale.webp" + "image": "/static/img/cards/primordial-nebula/common/void_scale.webp", + "expedition": { + "tags": [ + "lieu:observatoire", + "theme:veilleurs", + "personnage:salamandre", + "objet:pierre" + ] + } }, { "id": "astral-wolf-pendant", "collectionId": "primordial-nebula", "name": "Pendentif du Loup Astral", "description": "Les voyageurs le portent avant de traverser le vide. Il leur rappelle la promesse du Loup : protéger tous ceux qui voyagent sous le Soleil.", - "image": "/static/img/cards/primordial-nebula/common/astral_wolf_pendant.webp" + "image": "/static/img/cards/primordial-nebula/common/astral_wolf_pendant.webp", + "expedition": { + "tags": [ + "personnage:loup", + "theme:voyage", + "lieu:vide" + ] + } }, { "id": "celestial-fox-mask", "collectionId": "primordial-nebula", "name": "Masque du Renard Céleste", "description": "On le porte pendant les fêtes de la Lune Écarlate, puis on l'accroche à l'entrée de la maison. Le Kitsune saurait ainsi quelles familles guider.", - "image": "/static/img/cards/primordial-nebula/common/celestial_fox_mask.webp" + "image": "/static/img/cards/primordial-nebula/common/celestial_fox_mask.webp", + "expedition": { + "tags": [ + "personnage:kitsune", + "lieu:lune-ecarlate", + "theme:fete" + ] + } }, { "id": "azure-horizon-bamboo", "collectionId": "primordial-nebula", "name": "Bambou de l'Horizon Azur", "description": "Ce bambou bleuté pousse sur les îles les plus calmes. Les Veilleurs en font leurs lunettes, légères et assez solides pour résister au froid du vide.", - "image": "/static/img/cards/primordial-nebula/common/azure_horizon_bamboo.webp" + "image": "/static/img/cards/primordial-nebula/common/azure_horizon_bamboo.webp", + "expedition": { + "tags": [ + "theme:veilleurs", + "objet:lunette" + ] + } }, { "id": "solar-dawn-pebble", "collectionId": "primordial-nebula", "name": "Galet de l'Aube Solaire", "description": "Ramassés là où tombe le premier rayon du Soleil, ces galets dorés restent toujours tièdes. On en offre un à ceux qui partent pour un long voyage.", - "image": "/static/img/cards/primordial-nebula/common/solar_dawn_pebble.webp" + "image": "/static/img/cards/primordial-nebula/common/solar_dawn_pebble.webp", + "expedition": { + "tags": [ + "lieu:soleil", + "theme:voyage", + "objet:pierre" + ] + } }, { "id": "constellation-feather", "collectionId": "primordial-nebula", "name": "Plume des Constellations", "description": "Chaque plume perdue par la Pie est taillée pour écrire. Les Veilleurs n'utilisent qu'elles pour dessiner les constellations sur leurs cartes.", - "image": "/static/img/cards/primordial-nebula/common/constellation_feather.webp" + "image": "/static/img/cards/primordial-nebula/common/constellation_feather.webp", + "expedition": { + "tags": [ + "personnage:pie", + "theme:veilleurs", + "objet:ecriture" + ] + } }, { "id": "star-compass", "collectionId": "primordial-nebula", "name": "Boussole des Astres", "description": "Les îles bougent sans arrêt, mais les étoiles sœurs restent fiables. L'aiguille de cette boussole en suit une et montre la route à travers le vide.", - "image": "/static/img/cards/primordial-nebula/common/star_compass.webp" + "image": "/static/img/cards/primordial-nebula/common/star_compass.webp", + "expedition": { + "tags": [ + "objet:boussole", + "theme:voyage", + "theme:constellations" + ] + } }, { "id": "watchers-spyglass", "collectionId": "primordial-nebula", "name": "Lunette du Veilleur", "description": "Fabriquée avec le cuivre d'une météorite, c'est la première lunette des Veilleurs. Grâce à elle, ils ont compris que le ciel avait une histoire.", - "image": "/static/img/cards/primordial-nebula/common/watchers_spyglass.webp" + "image": "/static/img/cards/primordial-nebula/common/watchers_spyglass.webp", + "expedition": { + "tags": [ + "objet:lunette", + "theme:veilleurs", + "theme:cometes" + ] + } }, { "id": "forgotten-sky-map", "collectionId": "primordial-nebula", "name": "Carte du Ciel Oublié", "description": "Elle montre des étoiles éteintes et des îles qui n'existent plus. Les Veilleurs pensent qu'elle date de l'époque où le monde venait à peine de naître.", - "image": "/static/img/cards/primordial-nebula/common/forgotten_sky_map.webp" + "image": "/static/img/cards/primordial-nebula/common/forgotten_sky_map.webp", + "expedition": { + "tags": [ + "objet:carte", + "theme:veilleurs", + "theme:constellations" + ] + } }, { "id": "night-hourglass", "collectionId": "primordial-nebula", "name": "Sablier des Nuits", "description": "Son sable vient des dunes du Fennec : c'est la poussière de la Nébuleuse elle-même. Les Veilleurs le retournent chaque fois qu'ils changent d'équipe.", - "image": "/static/img/cards/primordial-nebula/common/night_hourglass.webp" + "image": "/static/img/cards/primordial-nebula/common/night_hourglass.webp", + "expedition": { + "tags": [ + "personnage:fennec", + "theme:poussiere", + "theme:veilleurs" + ] + } }, { "id": "astronomers-notebook", "collectionId": "primordial-nebula", "name": "Carnet de l'Astronome", "description": "Ses pages sont remplies de dessins d'îles, de calculs et de routes pas finies. Une note parle d'une île qu'on ne verrait que sous la Lune Écarlate.", - "image": "/static/img/cards/primordial-nebula/common/astronomers_notebook.webp" + "image": "/static/img/cards/primordial-nebula/common/astronomers_notebook.webp", + "expedition": { + "tags": [ + "objet:ecriture", + "theme:veilleurs", + "lieu:lune-ecarlate" + ] + } }, { "id": "pocket-astrolabe", "collectionId": "primordial-nebula", "name": "Astrolabe de Poche", "description": "Il sert à mesurer la hauteur des étoiles sœurs depuis n'importe quelle île. Sans lui, personne n'oserait voyager loin des îles qu'il connaît.", - "image": "/static/img/cards/primordial-nebula/common/pocket_astrolabe.webp" + "image": "/static/img/cards/primordial-nebula/common/pocket_astrolabe.webp", + "expedition": { + "tags": [ + "objet:boussole", + "theme:veilleurs", + "theme:voyage", + "theme:constellations" + ] + } }, { "id": "meteorite-fragment", "collectionId": "primordial-nebula", "name": "Fragment de Météorite", "description": "Tombé pendant une pluie d'étoiles, ce morceau de roche est veiné de cuivre. Pour les Veilleurs, c'est un bout de la Nébuleuse resté intact.", - "image": "/static/img/cards/primordial-nebula/common/meteorite_fragment.webp" + "image": "/static/img/cards/primordial-nebula/common/meteorite_fragment.webp", + "expedition": { + "tags": [ + "theme:cometes", + "objet:pierre", + "lieu:nebuleuse" + ] + } }, { "id": "stardust-vial", "collectionId": "primordial-nebula", "name": "Poussière d'Étoiles", "description": "Ramassée après les nuits d'étoiles filantes, cette poussière argentée est celle dont les îles sont faites. Les Veilleurs la gardent précieusement.", - "image": "/static/img/cards/primordial-nebula/common/stardust_vial.webp" + "image": "/static/img/cards/primordial-nebula/common/stardust_vial.webp", + "expedition": { + "tags": [ + "theme:poussiere", + "theme:veilleurs" + ] + } }, { "id": "moon-shard", "collectionId": "primordial-nebula", "name": "Éclat de Lune", "description": "Tombé de la Lune Pâle, ce caillou nacré brille doucement dans le noir. Les bateaux du ciel en accrochent un à l'avant pour qu'on les voie de loin.", - "image": "/static/img/cards/primordial-nebula/common/moon_shard.webp" + "image": "/static/img/cards/primordial-nebula/common/moon_shard.webp", + "expedition": { + "tags": [ + "lieu:lune-pale", + "objet:pierre", + "theme:voyage" + ] + } }, { "id": "nebula-pearl", "collectionId": "primordial-nebula", "name": "Perle de Nébuleuse", "description": "Les souffleurs de verre essaient d'y enfermer les couleurs de la Nébuleuse, telles que les racontent les légendes. Il n'en existe pas deux pareilles.", - "image": "/static/img/cards/primordial-nebula/common/nebula_pearl.webp" + "image": "/static/img/cards/primordial-nebula/common/nebula_pearl.webp", + "expedition": { + "tags": [ + "lieu:nebuleuse", + "objet:cristal" + ] + } }, { "id": "wandering-asteroid", "collectionId": "primordial-nebula", "name": "Petit Astéroïde Errant", "description": "Trop petit pour qu'on y vive, il flotte tout seul entre les îles. Les Veilleurs le surveillent : peut-être qu'un jour il deviendra une île lui aussi.", - "image": "/static/img/cards/primordial-nebula/common/wandering_asteroid.webp" + "image": "/static/img/cards/primordial-nebula/common/wandering_asteroid.webp", + "expedition": { + "tags": [ + "lieu:vide", + "theme:veilleurs" + ] + } }, { "id": "broken-saturn-ring", "collectionId": "primordial-nebula", "name": "Anneau de Saturne Brisé", "description": "Ce morceau de glace vient d'un anneau cassé quand deux îles se sont heurtées. Ses fines rayures rappellent que le monde n'a pas fini de changer.", - "image": "/static/img/cards/primordial-nebula/common/broken_saturn_ring.webp" + "image": "/static/img/cards/primordial-nebula/common/broken_saturn_ring.webp", + "expedition": { + "tags": [ + "lieu:vide", + "objet:pierre" + ] + } }, { "id": "twilight-lantern", "collectionId": "primordial-nebula", "name": "Lanterne du Crépuscule", "description": "Accrochée aux observatoires et à l'avant des bateaux du ciel, elle montre que quelqu'un veille. Sa lumière est assez douce pour laisser voir les étoiles.", - "image": "/static/img/cards/primordial-nebula/common/twilight_lantern.webp" + "image": "/static/img/cards/primordial-nebula/common/twilight_lantern.webp", + "expedition": { + "tags": [ + "objet:lanterne", + "theme:veilleurs", + "theme:voyage", + "lieu:observatoire" + ] + } }, { "id": "midnight-cup", "collectionId": "primordial-nebula", "name": "Tasse de Minuit", "description": "Elle appartenait à un Veilleur très distrait. Plongé dans ses calculs, il oubliait toujours sa boisson, qui finissait froide avant la fin de la nuit.", - "image": "/static/img/cards/primordial-nebula/common/midnight_cup.webp" + "image": "/static/img/cards/primordial-nebula/common/midnight_cup.webp", + "expedition": { + "tags": [ + "theme:veilleurs", + "theme:nuit" + ] + } }, { "id": "observatory-key", "collectionId": "primordial-nebula", "name": "Clé de l'Observatoire", "description": "Elle ouvre le premier observatoire, celui construit autour de l'Écaille du Néant. Son île s'est éloignée depuis, et plus personne ne sait où elle est.", - "image": "/static/img/cards/primordial-nebula/common/observatory_key.webp" + "image": "/static/img/cards/primordial-nebula/common/observatory_key.webp", + "expedition": { + "tags": [ + "lieu:observatoire", + "theme:veilleurs" + ] + } }, { "id": "astral-inkwell", "collectionId": "primordial-nebula", "name": "Encrier Astral", "description": "Son encre bleu nuit est mélangée à de la poussière de nébuleuse. Les cartes dessinées avec elle n'ont pas perdu leur couleur depuis des siècles.", - "image": "/static/img/cards/primordial-nebula/common/astral_inkwell.webp" + "image": "/static/img/cards/primordial-nebula/common/astral_inkwell.webp", + "expedition": { + "tags": [ + "objet:ecriture", + "theme:veilleurs", + "theme:poussiere" + ] + } }, { "id": "watchers-candle", "collectionId": "primordial-nebula", "name": "Bougie des Veilleurs", "description": "Une bougie est allumée au début de chaque nuit d'observation. Les plus vieux observatoires des îles gardent les traces de milliers de flammes.", - "image": "/static/img/cards/primordial-nebula/common/watchers_candle.webp" + "image": "/static/img/cards/primordial-nebula/common/watchers_candle.webp", + "expedition": { + "tags": [ + "lieu:observatoire", + "theme:veilleurs", + "theme:nuit" + ] + } }, { "id": "stellar-memory-box", "collectionId": "primordial-nebula", "name": "Boîte à Souvenirs Stellaires", "description": "Chaque Veilleur garde une boîte à souvenirs : un galet, une plume, un éclat de lune. Chaque objet lui rappelle une île visitée sous les étoiles.", - "image": "/static/img/cards/primordial-nebula/common/stellar_memory_box.webp" + "image": "/static/img/cards/primordial-nebula/common/stellar_memory_box.webp", + "expedition": { + "tags": [ + "theme:veilleurs", + "theme:voyage" + ] + } }, { "id": "first-crescent", "collectionId": "primordial-nebula", "name": "Premier Croissant", "description": "Le premier croissant de la Lune Écarlate marque le début d'un nouveau cycle. On allume alors une petite lumière pour que le Kitsune trouve les maisons.", - "image": "/static/img/cards/primordial-nebula/common/first_crescent.webp" + "image": "/static/img/cards/primordial-nebula/common/first_crescent.webp", + "expedition": { + "tags": [ + "lieu:lune-ecarlate", + "personnage:kitsune", + "theme:fete" + ] + } }, { "id": "lonely-star", "collectionId": "primordial-nebula", "name": "Étoile Solitaire", "description": "C'est une étoile sœur que la Pie n'a jamais réussi à relier aux autres. Seule dans son coin du ciel, elle écoute en silence les secrets des voyageurs.", - "image": "/static/img/cards/primordial-nebula/common/lonely_star.webp" + "image": "/static/img/cards/primordial-nebula/common/lonely_star.webp", + "expedition": { + "tags": [ + "theme:constellations", + "theme:voyage" + ] + } }, { "id": "cosmic-dust-cloud", "collectionId": "primordial-nebula", "name": "Nuage de Poussière Cosmique", "description": "Les Veilleurs l'observent avec un peu de peur et beaucoup d'espoir : ce nuage se resserre lentement, comme la Nébuleuse au tout début du monde.", - "image": "/static/img/cards/primordial-nebula/common/cosmic_dust_cloud.webp" + "image": "/static/img/cards/primordial-nebula/common/cosmic_dust_cloud.webp", + "expedition": { + "tags": [ + "lieu:nebuleuse", + "theme:veilleurs", + "theme:poussiere" + ] + } }, { "id": "horizon-glow", "collectionId": "primordial-nebula", "name": "Lueur de l'Horizon", "description": "Entre le coucher du Soleil et l'arrivée des premières étoiles, les voyageurs reprennent la route. Dans les îles, on appelle ce moment l'heure des départs.", - "image": "/static/img/cards/primordial-nebula/common/horizon_glow.webp" + "image": "/static/img/cards/primordial-nebula/common/horizon_glow.webp", + "expedition": { + "tags": [ + "theme:voyage", + "lieu:soleil" + ] + } }, { "id": "veiled-moon", "collectionId": "primordial-nebula", "name": "Lune Voilée", "description": "Quand la Lune Pâle se cache dans la brume, on dit qu'elle écoute les secrets des îles. Elle revient toujours sans rien en dire à personne.", - "image": "/static/img/cards/primordial-nebula/common/veiled_moon.webp" + "image": "/static/img/cards/primordial-nebula/common/veiled_moon.webp", + "expedition": { + "tags": [ + "lieu:lune-pale", + "theme:nuit" + ] + } }, { "id": "shooting-star", "collectionId": "primordial-nebula", "name": "Étoile Filante", "description": "Une étoile filante serait un rêve du Panda qui tombe. Les enfants des îles font un vœu en la voyant, en espérant qu'il devienne une île un jour.", - "image": "/static/img/cards/primordial-nebula/common/shooting_star.webp" + "image": "/static/img/cards/primordial-nebula/common/shooting_star.webp", + "expedition": { + "tags": [ + "personnage:panda", + "theme:reves" + ] + } }, { "id": "mythic-card-pull", @@ -977,70 +1919,132 @@ "image": "/static/img/cards/astral-genesis/legendary/mythic_card_pull.webp", "cutoutImage": "/static/img/cards/astral-genesis/legendary/mythic_card_pull__cutout.webp", "fullImage": "/static/img/cards/astral-genesis/legendary/mythic_card_pull__full.webp", - "fullCutoutImage": "/static/img/cards/astral-genesis/legendary/mythic_card_pull__full__cutout.webp" + "fullCutoutImage": "/static/img/cards/astral-genesis/legendary/mythic_card_pull__full__cutout.webp", + "expedition": { + "tags": [ + "personnage:dragon", + "theme:collection" + ] + } }, { "id": "crimson-card-trade", "collectionId": "astral-genesis", "name": "L'Échange Écarlate", "description": "Sous la Lune Écarlate, le Kitsune tend une carte à la Pie. Personne ne sait qui a fait la meilleure affaire, mais ils repartent tous les deux ravis.", - "image": "/static/img/cards/astral-genesis/epic/crimson_card_trade.webp" + "image": "/static/img/cards/astral-genesis/epic/crimson_card_trade.webp", + "expedition": { + "tags": [ + "personnage:kitsune", + "personnage:pie", + "lieu:lune-ecarlate", + "theme:collection" + ] + } }, { "id": "dawn-card-trade", "collectionId": "astral-genesis", "name": "L'Échange de l'Aube", "description": "Au lever du jour, le Capybara de l'Aube Solaire et le Panda de la Voie Lactée échangent une carte. Leur sourire vaut bien plus que sa rareté.", - "image": "/static/img/cards/astral-genesis/epic/dawn_card_trade.webp" + "image": "/static/img/cards/astral-genesis/epic/dawn_card_trade.webp", + "expedition": { + "tags": [ + "personnage:capybara", + "personnage:panda", + "lieu:soleil", + "theme:collection" + ] + } }, { "id": "astral-pack-opening", "collectionId": "astral-genesis", "name": "La Découverte Astrale", "description": "Le Dragon du Néant Étoilé entrouvre son paquet. Avant la première carte, il savoure cet instant où toutes les surprises restent possibles.", - "image": "/static/img/cards/astral-genesis/rare/astral_pack_opening.webp" + "image": "/static/img/cards/astral-genesis/rare/astral_pack_opening.webp", + "expedition": { + "tags": [ + "personnage:dragon", + "theme:collection" + ] + } }, { "id": "next-booster-wait", "collectionId": "astral-genesis", "name": "L'Attente du Prochain Paquet", "description": "Devant un sablier et un paquet scellé, le Dragon du Néant Étoilé guette chaque grain, persuadé que le temps ralentit juste avant l'ouverture.", - "image": "/static/img/cards/astral-genesis/rare/next_booster_wait.webp" + "image": "/static/img/cards/astral-genesis/rare/next_booster_wait.webp", + "expedition": { + "tags": [ + "personnage:dragon", + "theme:collection" + ] + } }, { "id": "collectors-treasure", "collectionId": "astral-genesis", "name": "Le Trésor du Collectionneur", "description": "Devant son classeur, le Dragon du Néant Étoilé contemple ses cartes. Précieuse ou ordinaire, chacune lui rappelle un moment heureux.", - "image": "/static/img/cards/astral-genesis/rare/collectors_treasure.webp" + "image": "/static/img/cards/astral-genesis/rare/collectors_treasure.webp", + "expedition": { + "tags": [ + "personnage:dragon", + "theme:collection", + "theme:tresor" + ] + } }, { "id": "astral-booster", "collectionId": "astral-genesis", "name": "Paquet Astral", "description": "Sous son emballage violet et or se cachent quelques cartes inconnues. Pour les collectionneurs, le plaisir commence bien avant la première ouverture.", - "image": "/static/img/cards/astral-genesis/common/astral_booster.webp" + "image": "/static/img/cards/astral-genesis/common/astral_booster.webp", + "expedition": { + "tags": [ + "theme:collection" + ] + } }, { "id": "collector-binder", "collectionId": "astral-genesis", "name": "Classeur du Collectionneur", "description": "Ses pochettes accueillent les découvertes les plus modestes comme les plus extraordinaires. Chaque emplacement rempli raconte une histoire.", - "image": "/static/img/cards/astral-genesis/common/collector_binder.webp" + "image": "/static/img/cards/astral-genesis/common/collector_binder.webp", + "expedition": { + "tags": [ + "theme:collection" + ] + } }, { "id": "astral-card-stack", "collectionId": "astral-genesis", "name": "Pile de Cartes Astrales", "description": "Des cartes soigneusement empilées après une longue séance d'ouverture. Il suffit d'en retourner une pour revivre l'émotion de sa découverte.", - "image": "/static/img/cards/astral-genesis/common/astral_card_stack.webp" + "image": "/static/img/cards/astral-genesis/common/astral_card_stack.webp", + "expedition": { + "tags": [ + "theme:collection" + ] + } }, { "id": "celestial-storage-box", "collectionId": "astral-genesis", "name": "Coffret de Rangement Céleste", "description": "Ce coffret aux constellations dorées protège les cartes de la poussière et du temps. Son propriétaire y conserve surtout celles qu'il aime retrouver.", - "image": "/static/img/cards/astral-genesis/common/celestial_storage_box.webp" + "image": "/static/img/cards/astral-genesis/common/celestial_storage_box.webp", + "expedition": { + "tags": [ + "theme:collection", + "theme:constellations" + ] + } }, { "id": "stardust-dragon", @@ -1048,7 +2052,13 @@ "name": "Dragon de Poussière d'Étoiles", "description": "Les yeux clos, ce jeune dragon danse sous une pluie d'or. Chaque écaille qu'il perd redevient une étoile, et c'est elle qui donne sa lueur à la poussière du ciel.", "image": "/static/img/cards/stardust/legendary/stardust_dragon.webp", - "fullImage": "/static/img/cards/stardust/legendary/stardust_dragon__full.webp" + "fullImage": "/static/img/cards/stardust/legendary/stardust_dragon__full.webp", + "expedition": { + "tags": [ + "personnage:dragon", + "theme:poussiere" + ] + } }, { "id": "night-of-return-dragon", @@ -1057,7 +2067,21 @@ "description": "Pendant la Longue Nuit, le Dragon rapproche les îles. Le soir du Retour, il souffle une poussière dorée qui allume les lanternes : la fête peut commencer.", "image": "/static/img/cards/long-night/legendary/night_of_return_dragon.webp", "fullImage": "/static/img/cards/long-night/legendary/night_of_return_dragon__full.webp", - "fullCutoutImage": "/static/img/cards/long-night/legendary/night_of_return_dragon__full__cutout.webp" + "fullCutoutImage": "/static/img/cards/long-night/legendary/night_of_return_dragon__full__cutout.webp", + "expedition": { + "tags": [ + "personnage:dragon", + "theme:hiver", + "theme:fete", + "objet:lanterne" + ], + "profile": { + "bravoure": 35, + "endurance": 35, + "fortune": 15, + "orientation": 15 + } + } }, { "id": "midnight-snowy-owl", @@ -1066,7 +2090,21 @@ "description": "Perché en haut du grand sapin, le Harfang attend minuit. Quand il ouvre ses ailes et pousse son cri, le premier feu d'artifice de l'année s'envole.", "image": "/static/img/cards/long-night/legendary/midnight_snowy_owl.webp", "fullImage": "/static/img/cards/long-night/legendary/midnight_snowy_owl__full.webp", - "fullCutoutImage": "/static/img/cards/long-night/legendary/midnight_snowy_owl__full__cutout.webp" + "fullCutoutImage": "/static/img/cards/long-night/legendary/midnight_snowy_owl__full__cutout.webp", + "expedition": { + "tags": [ + "personnage:hibou", + "theme:hiver", + "theme:fete", + "theme:nuit" + ], + "profile": { + "bravoure": 20, + "endurance": 30, + "fortune": 20, + "orientation": 30 + } + } }, { "id": "gift-sleigh-reindeer", @@ -1075,196 +2113,395 @@ "description": "Pendant la Longue Nuit, le Renne file d'île en île sur les courants gelés. Son traîneau déborde de cadeaux, et ses clochettes annoncent son arrivée.", "image": "/static/img/cards/long-night/legendary/gift_sleigh_reindeer.webp", "fullImage": "/static/img/cards/long-night/legendary/gift_sleigh_reindeer__full.webp", - "fullCutoutImage": "/static/img/cards/long-night/legendary/gift_sleigh_reindeer__full__cutout.webp" + "fullCutoutImage": "/static/img/cards/long-night/legendary/gift_sleigh_reindeer__full__cutout.webp", + "expedition": { + "tags": [ + "theme:hiver", + "theme:voyage", + "lieu:courants", + "objet:cadeau" + ], + "profile": { + "bravoure": 15, + "endurance": 35, + "fortune": 20, + "orientation": 30 + } + } }, { "id": "grand-feast-bear", "collectionId": "long-night", "name": "Ours du Grand Réveillon", "description": "Chaque année, l'Ours prépare le repas du réveillon pour toutes les îles. Il goûte chaque plat, juste pour vérifier, dit-il, que tout est parfait.", - "image": "/static/img/cards/long-night/epic/grand_feast_bear.webp" + "image": "/static/img/cards/long-night/epic/grand_feast_bear.webp", + "expedition": { + "tags": [ + "personnage:ours", + "theme:hiver", + "theme:fete" + ] + } }, { "id": "golden-ribbon-ermine", "collectionId": "long-night", "name": "Hermine aux Rubans d'Or", "description": "Rubans, papier, ciseaux : l'Hermine emballe les cadeaux plus vite que tout le monde. Ses nœuds dorés sont si beaux qu'on hésite à les défaire.", - "image": "/static/img/cards/long-night/epic/golden_ribbon_ermine.webp" + "image": "/static/img/cards/long-night/epic/golden_ribbon_ermine.webp", + "expedition": { + "tags": [ + "theme:hiver", + "theme:fete", + "objet:cadeau" + ] + } }, { "id": "gift-bearer-penguin", "collectionId": "long-night", "name": "Manchot Porteur de Présents", "description": "Les manchots livrent les cadeaux à pied sur la glace, en file indienne. Le premier porte toujours le plus gros paquet, même s'il ne voit plus devant lui.", - "image": "/static/img/cards/long-night/epic/gift_bearer_penguin.webp" + "image": "/static/img/cards/long-night/epic/gift_bearer_penguin.webp", + "expedition": { + "tags": [ + "personnage:manchot", + "lieu:glaces", + "theme:hiver", + "objet:cadeau" + ] + } }, { "id": "fireworks-lynx", "collectionId": "long-night", "name": "Lynx des Feux d'Artifice", "description": "À minuit, le lynx bondit au milieu des feux d'artifice sans jamais se brûler. On dit que le voir passer porte chance pour toute l'année qui commence.", - "image": "/static/img/cards/long-night/epic/fireworks_lynx.webp" + "image": "/static/img/cards/long-night/epic/fireworks_lynx.webp", + "expedition": { + "tags": [ + "personnage:lynx", + "theme:fete", + "theme:nuit", + "theme:hiver" + ] + } }, { "id": "bundled-little-dragon", "collectionId": "long-night", "name": "Petit Dragon Emmitouflé", "description": "La première fois qu'il a vu la neige, le petit Dragon a voulu goûter chaque flocon. Son écharpe, bien trop grande, lui a été tricotée par les habitants.", - "image": "/static/img/cards/long-night/epic/bundled_little_dragon.webp" + "image": "/static/img/cards/long-night/epic/bundled_little_dragon.webp", + "expedition": { + "tags": [ + "personnage:dragon", + "theme:hiver" + ] + } }, { "id": "lunar-ice-seal", "collectionId": "long-night", "name": "Phoque des Glaces Lunaires", "description": "Il dort sur les plaques de glace qui flottent au bord des îles. Les nuits de pleine lune, la glace autour de lui brille comme un grand miroir argenté.", - "image": "/static/img/cards/long-night/epic/lunar_ice_seal.webp" + "image": "/static/img/cards/long-night/epic/lunar_ice_seal.webp", + "expedition": { + "tags": [ + "lieu:glaces", + "theme:hiver", + "theme:nuit" + ] + } }, { "id": "starry-snowdrift-hare", "collectionId": "long-night", "name": "Lièvre des Congères Étoilées", "description": "Quand la Longue Nuit arrive, son pelage devient blanc comme la neige. À chaque bond, il soulève une poudre qui scintille longtemps, comme des étoiles.", - "image": "/static/img/cards/long-night/epic/starry_snowdrift_hare.webp" + "image": "/static/img/cards/long-night/epic/starry_snowdrift_hare.webp", + "expedition": { + "tags": [ + "theme:hiver", + "theme:poussiere" + ] + } }, { "id": "cookie-thief-raccoon", "collectionId": "long-night", "name": "Raton Laveur Chapardeur de Biscuits", "description": "Le soir du réveillon, les biscuits en forme d'étoile disparaissent un par un. Le raton laveur jure qu'il n'y est pour rien, la bouche encore pleine.", - "image": "/static/img/cards/long-night/rare/cookie_thief_raccoon.webp" + "image": "/static/img/cards/long-night/rare/cookie_thief_raccoon.webp", + "expedition": { + "tags": [ + "personnage:raton-laveur", + "theme:fete", + "theme:hiver" + ] + } }, { "id": "frost-wool-sheep", "collectionId": "long-night", "name": "Mouton à la Laine de Givre", "description": "Pendant la Longue Nuit, sa laine se couvre de givre et brille comme du sucre. C'est avec elle qu'on tricote les bonnets et les écharpes de l'hiver.", - "image": "/static/img/cards/long-night/rare/frost_wool_sheep.webp" + "image": "/static/img/cards/long-night/rare/frost_wool_sheep.webp", + "expedition": { + "tags": [ + "theme:hiver" + ] + } }, { "id": "garland-hedgehog", "collectionId": "long-night", "name": "Hérisson à la Guirlande", "description": "En voulant aider à décorer le sapin, il s'est emmêlé dans la guirlande. Ses épines brillent maintenant de toutes les couleurs, et il en est très fier.", - "image": "/static/img/cards/long-night/rare/garland_hedgehog.webp" + "image": "/static/img/cards/long-night/rare/garland_hedgehog.webp", + "expedition": { + "tags": [ + "personnage:herisson", + "theme:fete", + "theme:hiver" + ] + } }, { "id": "gift-wrap-kitten", "collectionId": "long-night", "name": "Chaton dans le Papier Cadeau", "description": "Le chaton se cache dans le papier cadeau dès qu'on veut emballer un présent. Pour lui, le plus beau des cadeaux, c'est le papier lui-même.", - "image": "/static/img/cards/long-night/rare/gift_wrap_kitten.webp" + "image": "/static/img/cards/long-night/rare/gift_wrap_kitten.webp", + "expedition": { + "tags": [ + "theme:fete", + "objet:cadeau", + "theme:hiver" + ] + } }, { "id": "greeting-card-owl", "collectionId": "long-night", "name": "Chouette des Cartes de Vœux", "description": "Avec sa sacoche pleine de lettres, la chouette vole d'île en île pendant la Longue Nuit. Elle apporte les cartes de vœux de ceux qui vivent trop loin.", - "image": "/static/img/cards/long-night/rare/greeting_card_owl.webp" + "image": "/static/img/cards/long-night/rare/greeting_card_owl.webp", + "expedition": { + "tags": [ + "personnage:hibou", + "theme:voyage", + "theme:hiver", + "objet:ecriture" + ] + } }, { "id": "mistletoe-bullfinch", "collectionId": "long-night", "name": "Bouvreuil du Gui", "description": "Il se pose toujours sur la branche de gui accrochée à l'entrée des maisons. Quand on le voit, la tradition veut qu'on s'embrasse juste en dessous.", - "image": "/static/img/cards/long-night/rare/mistletoe_bullfinch.webp" + "image": "/static/img/cards/long-night/rare/mistletoe_bullfinch.webp", + "expedition": { + "tags": [ + "theme:fete", + "theme:hiver" + ] + } }, { "id": "skating-otter", "collectionId": "long-night", "name": "Loutre Patineuse des Lacs Gelés", "description": "Quand les lacs gèlent, la loutre passe ses journées à glisser sur le ventre. Elle apprend même à patiner aux enfants des îles, avec plus ou moins de succès.", - "image": "/static/img/cards/long-night/rare/skating_otter.webp" + "image": "/static/img/cards/long-night/rare/skating_otter.webp", + "expedition": { + "tags": [ + "personnage:loutre", + "lieu:glaces", + "theme:hiver" + ] + } }, { "id": "snow-dream-marmot", "collectionId": "long-night", "name": "Marmotte des Songes de Neige", "description": "Elle s'endort au début de la Longue Nuit et ne se réveille qu'au retour du Soleil. Pendant ce temps, elle rêve des fêtes qu'elle ne voit jamais.", - "image": "/static/img/cards/long-night/rare/snow_dream_marmot.webp" + "image": "/static/img/cards/long-night/rare/snow_dream_marmot.webp", + "expedition": { + "tags": [ + "theme:reves", + "theme:hiver" + ] + } }, { "id": "winter-stash-squirrel", "collectionId": "long-night", "name": "Écureuil des Provisions d'Hiver", "description": "Toute l'année, il cache des noisettes dans le creux des arbres. Quand la Longue Nuit arrive, il en a tellement qu'il partage ses réserves avec ses voisins.", - "image": "/static/img/cards/long-night/rare/winter_stash_squirrel.webp" + "image": "/static/img/cards/long-night/rare/winter_stash_squirrel.webp", + "expedition": { + "tags": [ + "personnage:ecureuil", + "theme:hiver" + ] + } }, { "id": "wool-hat-fox-cub", "collectionId": "long-night", "name": "Renardeau au Bonnet de Laine", "description": "Son bonnet de laine lui tombe sur les yeux, mais il refuse de l'enlever. C'est le premier cadeau qu'il a reçu, lors de sa toute première Longue Nuit.", - "image": "/static/img/cards/long-night/rare/wool_hat_fox_cub.webp" + "image": "/static/img/cards/long-night/rare/wool_hat_fox_cub.webp", + "expedition": { + "tags": [ + "personnage:renard", + "theme:hiver", + "objet:cadeau" + ] + } }, { "id": "celestial-gift", "collectionId": "long-night", "name": "Présent Céleste", "description": "Emballé dans un papier bleu nuit couvert de constellations, ce cadeau brille un peu. Personne ne sait ce qu'il contient, et c'est ce qui le rend si précieux.", - "image": "/static/img/cards/long-night/common/celestial_gift.webp" + "image": "/static/img/cards/long-night/common/celestial_gift.webp", + "expedition": { + "tags": [ + "objet:cadeau", + "theme:constellations", + "theme:fete" + ] + } }, { "id": "midnight-firework", "collectionId": "long-night", "name": "Feu d'Artifice de Minuit", "description": "À minuit, le ciel de l'archipel s'illumine d'or et de violet. Les feux d'artifice se reflètent sur les lacs gelés et saluent l'année qui commence.", - "image": "/static/img/cards/long-night/common/midnight_firework.webp" + "image": "/static/img/cards/long-night/common/midnight_firework.webp", + "expedition": { + "tags": [ + "theme:fete", + "theme:nuit", + "lieu:glaces" + ] + } }, { "id": "reindeer-constellation", "collectionId": "long-night", "name": "Constellation du Renne", "description": "Elle n'apparaît que pendant la Longue Nuit. Les Veilleurs disent qu'elle montre la route du Renne, d'île en île, sous les aurores d'hiver.", - "image": "/static/img/cards/long-night/common/reindeer_constellation.webp" + "image": "/static/img/cards/long-night/common/reindeer_constellation.webp", + "expedition": { + "tags": [ + "theme:constellations", + "theme:veilleurs", + "theme:aurores", + "theme:hiver" + ] + } }, { "id": "reunion-lantern", "collectionId": "long-night", "name": "Lanterne des Retrouvailles", "description": "Ces lanternes rouges sont accrochées le long des ponts couverts entre les îles. On les allume pour guider ceux qui viennent fêter les retrouvailles.", - "image": "/static/img/cards/long-night/common/reunion_lantern.webp" + "image": "/static/img/cards/long-night/common/reunion_lantern.webp", + "expedition": { + "tags": [ + "objet:lanterne", + "theme:fete", + "theme:voyage" + ] + } }, { "id": "reunited-islands-tree", "collectionId": "long-night", "name": "Sapin des Îles Réunies", "description": "Pendant la Longue Nuit, chaque île décore un sapin sur sa grande place. Les cadeaux s'y entassent jusqu'au matin, sous la lumière des guirlandes.", - "image": "/static/img/cards/long-night/common/reunited_islands_tree.webp" + "image": "/static/img/cards/long-night/common/reunited_islands_tree.webp", + "expedition": { + "tags": [ + "theme:fete", + "theme:hiver", + "objet:cadeau" + ] + } }, { "id": "snowman", "collectionId": "long-night", "name": "Bonhomme de Neige", "description": "Ses yeux sont des cailloux tombés de la Lune Pâle. Les enfants le construisent au bord de leur île, pour qu'il salue les voyageurs qui arrivent.", - "image": "/static/img/cards/long-night/common/snowman.webp" + "image": "/static/img/cards/long-night/common/snowman.webp", + "expedition": { + "tags": [ + "theme:hiver", + "lieu:lune-pale", + "theme:voyage" + ] + } }, { "id": "starry-snowflake", "collectionId": "long-night", "name": "Flocon Étoilé", "description": "Pendant la Longue Nuit, certains flocons gardent un peu de la lumière des étoiles. Ils brillent quelques instants dans la main avant de fondre.", - "image": "/static/img/cards/long-night/common/starry_snowflake.webp" + "image": "/static/img/cards/long-night/common/starry_snowflake.webp", + "expedition": { + "tags": [ + "theme:hiver", + "theme:poussiere" + ] + } }, { "id": "star-yule-log", "collectionId": "long-night", "name": "Bûche des Étoiles", "description": "Ce gâteau roulé au chocolat est décoré de petites étoiles dorées. C'est l'Ours qui en a donné la recette, et chaque île jure avoir la meilleure version.", - "image": "/static/img/cards/long-night/common/star_yule_log.webp" + "image": "/static/img/cards/long-night/common/star_yule_log.webp", + "expedition": { + "tags": [ + "personnage:ours", + "theme:fete", + "theme:hiver" + ] + } }, { "id": "tree-top-star", "collectionId": "long-night", "name": "Étoile du Sommet", "description": "Le moment préféré de la fête : poser l'étoile en haut du sapin. On raconte que c'est un morceau d'étoile sœur, rapporté par la Pie il y a très longtemps.", - "image": "/static/img/cards/long-night/common/tree_top_star.webp" + "image": "/static/img/cards/long-night/common/tree_top_star.webp", + "expedition": { + "tags": [ + "theme:fete", + "personnage:pie", + "theme:constellations" + ] + } }, { "id": "watchers-hot-chocolate", "collectionId": "long-night", "name": "Chocolat Chaud du Veilleur", "description": "Pendant les longues nuits d'hiver, les Veilleurs observent le ciel une tasse à la main. Avec une pincée de poussière dorée, on en oublie vite le froid.", - "image": "/static/img/cards/long-night/common/watchers_hot_chocolate.webp" + "image": "/static/img/cards/long-night/common/watchers_hot_chocolate.webp", + "expedition": { + "tags": [ + "theme:veilleurs", + "theme:hiver", + "theme:nuit" + ] + } }, { "id": "golden-block-hero-dragon", @@ -1272,7 +2509,20 @@ "name": "Dragon, Héros du Bloc Doré", "description": "Sur l'île des plateformes, chaque bloc doré cache une pièce. Le Dragon du Néant Étoilé saute si haut pour les frapper qu'il en oublie qu'il sait voler.", "image": "/static/img/cards/dream-arcade/legendary/golden_block_hero_dragon.webp", - "fullImage": "/static/img/cards/dream-arcade/legendary/golden_block_hero_dragon__full.webp" + "fullImage": "/static/img/cards/dream-arcade/legendary/golden_block_hero_dragon__full.webp", + "expedition": { + "tags": [ + "personnage:dragon", + "lieu:iles-jeux", + "theme:tresor" + ], + "profile": { + "bravoure": 40, + "endurance": 20, + "fortune": 30, + "orientation": 10 + } + } }, { "id": "ancient-blade-kitsune", @@ -1280,7 +2530,21 @@ "name": "Kitsune, Gardien de l'Épée Ancienne", "description": "Au cœur d'une forêt rêvée, une épée attendait son héros. Le Kitsune de la Lune Écarlate l'a levée vers le ciel, et toute la clairière s'est mise à briller.", "image": "/static/img/cards/dream-arcade/legendary/ancient_blade_kitsune.webp", - "fullImage": "/static/img/cards/dream-arcade/legendary/ancient_blade_kitsune__full.webp" + "fullImage": "/static/img/cards/dream-arcade/legendary/ancient_blade_kitsune__full.webp", + "expedition": { + "tags": [ + "personnage:kitsune", + "lieu:iles-jeux", + "theme:aventure", + "objet:arme" + ], + "profile": { + "bravoure": 35, + "endurance": 15, + "fortune": 15, + "orientation": 35 + } + } }, { "id": "star-trainer-panda", @@ -1288,7 +2552,21 @@ "name": "Panda, Dresseur des Étoiles", "description": "Le Panda de la Voie Lactée ne fait pas que rêver les îles-jeux : il y joue aussi. Avec ses partenaires, il fouille les hautes herbes pour se faire de nouveaux amis.", "image": "/static/img/cards/dream-arcade/legendary/star_trainer_panda.webp", - "fullImage": "/static/img/cards/dream-arcade/legendary/star_trainer_panda__full.webp" + "fullImage": "/static/img/cards/dream-arcade/legendary/star_trainer_panda__full.webp", + "expedition": { + "tags": [ + "personnage:panda", + "lieu:iles-jeux", + "theme:aventure", + "theme:reves" + ], + "profile": { + "bravoure": 20, + "endurance": 20, + "fortune": 40, + "orientation": 20 + } + } }, { "id": "aurora-bolt-wolf", @@ -1296,7 +2574,20 @@ "name": "Loup, Éclair des Aurores", "description": "Le Loup des Aurores a trouvé une île faite pour lui : des boucles, des pentes et des anneaux dorés. Il y court si vite qu'il laisse une aurore derrière lui.", "image": "/static/img/cards/dream-arcade/legendary/aurora_bolt_wolf.webp", - "fullImage": "/static/img/cards/dream-arcade/legendary/aurora_bolt_wolf__full.webp" + "fullImage": "/static/img/cards/dream-arcade/legendary/aurora_bolt_wolf__full.webp", + "expedition": { + "tags": [ + "personnage:loup", + "lieu:iles-jeux", + "theme:aurores" + ], + "profile": { + "bravoure": 45, + "endurance": 25, + "fortune": 15, + "orientation": 15 + } + } }, { "id": "cube-world-magpie", @@ -1304,7 +2595,21 @@ "name": "Pie, Bâtisseuse du Monde Cube", "description": "Sur l'île des cubes, tout se casse et tout se construit. La Pie des Constellations y creuse la pierre pour trouver les gemmes les plus brillantes.", "image": "/static/img/cards/dream-arcade/legendary/cube_world_magpie.webp", - "fullImage": "/static/img/cards/dream-arcade/legendary/cube_world_magpie__full.webp" + "fullImage": "/static/img/cards/dream-arcade/legendary/cube_world_magpie__full.webp", + "expedition": { + "tags": [ + "personnage:pie", + "lieu:iles-jeux", + "objet:cristal", + "theme:tresor" + ], + "profile": { + "bravoure": 25, + "endurance": 20, + "fortune": 35, + "orientation": 20 + } + } }, { "id": "peaceful-isle-mayor-capybara", @@ -1312,315 +2617,628 @@ "name": "Capybara, Maire de l'Île Paisible", "description": "Sur l'île la plus calme de toutes, le Capybara de l'Aube Solaire est devenu maire. Chaque matin, il pêche au bout du ponton, et le Soleil se lève tranquille.", "image": "/static/img/cards/dream-arcade/legendary/peaceful_isle_mayor_capybara.webp", - "fullImage": "/static/img/cards/dream-arcade/legendary/peaceful_isle_mayor_capybara__full.webp" + "fullImage": "/static/img/cards/dream-arcade/legendary/peaceful_isle_mayor_capybara__full.webp", + "expedition": { + "tags": [ + "personnage:capybara", + "lieu:iles-jeux", + "lieu:soleil", + "theme:eau" + ], + "profile": { + "bravoure": 15, + "endurance": 40, + "fortune": 30, + "orientation": 15 + } + } }, { "id": "rainbow-grand-prix", "collectionId": "dream-arcade", "name": "Grand Prix de l'Arc-en-ciel", "description": "Une route arc-en-ciel relie deux îles-jeux. La Loutre et l'Écureuil y font la course chaque soir, et plus personne ne se souvient qui a gagné la première.", - "image": "/static/img/cards/dream-arcade/epic/rainbow_grand_prix.webp" + "image": "/static/img/cards/dream-arcade/epic/rainbow_grand_prix.webp", + "expedition": { + "tags": [ + "personnage:loutre", + "personnage:ecureuil", + "lieu:iles-jeux", + "theme:voyage" + ] + } }, { "id": "lynx-panther-duel", "collectionId": "dream-arcade", "name": "Duel du Lynx et de la Panthère", "description": "Le Lynx et la Panthère s'entraînent sur le toit d'un temple rêvé. Leurs combats sont amicaux : le perdant offre le thé, et c'est souvent le Lynx.", - "image": "/static/img/cards/dream-arcade/epic/lynx_panther_duel.webp" + "image": "/static/img/cards/dream-arcade/epic/lynx_panther_duel.webp", + "expedition": { + "tags": [ + "personnage:lynx", + "personnage:panthere", + "lieu:iles-jeux", + "theme:aventure" + ] + } }, { "id": "star-gobbler-axolotl", "collectionId": "dream-arcade", "name": "Axolotl Gourmand d'Étoiles", "description": "Sur une île toute ronde, l'Axolotl a découvert qu'il pouvait tout aspirer. Il gonfle comme un ballon et avale les étoiles qui passent, juste pour le goût.", - "image": "/static/img/cards/dream-arcade/epic/star_gobbler_axolotl.webp" + "image": "/static/img/cards/dream-arcade/epic/star_gobbler_axolotl.webp", + "expedition": { + "tags": [ + "personnage:axolotl", + "lieu:iles-jeux" + ] + } }, { "id": "pearl-maze-hedgehog", "collectionId": "dream-arcade", "name": "Hérisson du Labyrinthe aux Perles", "description": "Roulé en boule, le Hérisson dévale le labyrinthe en mangeant les perles. Quatre petites méduses le poursuivent : c'est leur jeu préféré.", - "image": "/static/img/cards/dream-arcade/epic/pearl_maze_hedgehog.webp" + "image": "/static/img/cards/dream-arcade/epic/pearl_maze_hedgehog.webp", + "expedition": { + "tags": [ + "personnage:herisson", + "lieu:iles-jeux" + ] + } }, { "id": "falling-blocks-chameleon", "collectionId": "dream-arcade", "name": "Caméléon des Blocs Tombants", "description": "Sur cette île, des blocs tombent du ciel sans arrêt. Le Caméléon les attrape et les range sans laisser de trou, en prenant la couleur de chacun.", - "image": "/static/img/cards/dream-arcade/epic/falling_blocks_chameleon.webp" + "image": "/static/img/cards/dream-arcade/epic/falling_blocks_chameleon.webp", + "expedition": { + "tags": [ + "personnage:cameleon", + "lieu:iles-jeux" + ] + } }, { "id": "shadow-mage-owl", "collectionId": "dream-arcade", "name": "Hibou, Mage des Ombres", "description": "Sous son grand chapeau, on ne voit que ses yeux. Le Hibou a appris la magie sur une île-jeu, et ses sorts de feu éclairent les ruines la nuit.", - "image": "/static/img/cards/dream-arcade/epic/shadow_mage_owl.webp" + "image": "/static/img/cards/dream-arcade/epic/shadow_mage_owl.webp", + "expedition": { + "tags": [ + "personnage:hibou", + "lieu:iles-jeux", + "theme:aventure", + "theme:nuit" + ] + } }, { "id": "golden-tree-knight-deer", "collectionId": "dream-arcade", "name": "Cerf, Chevalier de l'Arbre d'Or", "description": "Après un long voyage, le Cerf se repose devant l'immense Arbre d'Or. La Salamandre s'est roulée en boule près de lui pour lui tenir chaud.", - "image": "/static/img/cards/dream-arcade/epic/golden_tree_knight_deer.webp" + "image": "/static/img/cards/dream-arcade/epic/golden_tree_knight_deer.webp", + "expedition": { + "tags": [ + "personnage:cerf", + "personnage:salamandre", + "lieu:iles-jeux", + "theme:aventure", + "theme:voyage" + ] + } }, { "id": "crimson-crypt-bat", "collectionId": "dream-arcade", "name": "Chauve-souris des Cryptes Écarlates", "description": "Au fond d'une crypte rêvée, un grand démon rouge garde son trésor. La Chauve-souris et son petit squelette n'ont pas peur : ils sont venus pour le butin.", - "image": "/static/img/cards/dream-arcade/epic/crimson_crypt_bat.webp" + "image": "/static/img/cards/dream-arcade/epic/crimson_crypt_bat.webp", + "expedition": { + "tags": [ + "personnage:chauve-souris", + "lieu:iles-jeux", + "theme:aventure", + "theme:tresor" + ] + } }, { "id": "wyvern-hunter-fennec", "collectionId": "dream-arcade", "name": "Fennec, Chasseur de Wyverne", "description": "Le Fennec porte une épée plus grande que lui. Avec son petit chat compagnon, il part chasser l'énorme wyverne rouge qui survole la vallée.", - "image": "/static/img/cards/dream-arcade/epic/wyvern_hunter_fennec.webp" + "image": "/static/img/cards/dream-arcade/epic/wyvern_hunter_fennec.webp", + "expedition": { + "tags": [ + "personnage:fennec", + "lieu:iles-jeux", + "theme:aventure", + "objet:arme" + ] + } }, { "id": "portal-frog", "collectionId": "dream-arcade", "name": "Grenouille des Portails", "description": "La Grenouille a trouvé un appareil qui ouvre des passages, un peu comme le Kitsune. Elle saute dans un portail bleu et ressort par l'orange, en plein vol.", - "image": "/static/img/cards/dream-arcade/epic/portal_frog.webp" + "image": "/static/img/cards/dream-arcade/epic/portal_frog.webp", + "expedition": { + "tags": [ + "personnage:grenouille", + "lieu:iles-jeux", + "theme:passages" + ] + } }, { "id": "egg-tossing-gecko", "collectionId": "dream-arcade", "name": "Gecko Lanceur d'Œufs", "description": "Le Gecko porte une petite selle rouge et lance des œufs à pois verts. Sur son île-jeu, il en garde toujours un d'avance, au cas où.", - "image": "/static/img/cards/dream-arcade/rare/egg_tossing_gecko.webp" + "image": "/static/img/cards/dream-arcade/rare/egg_tossing_gecko.webp", + "expedition": { + "tags": [ + "personnage:gecko", + "lieu:iles-jeux" + ] + } }, { "id": "impostor-raccoon", "collectionId": "dream-arcade", "name": "Raton Laveur Imposteur", "description": "Dans le vaisseau rêvé, quelqu'un sort des aérations. Le Raton Laveur jure qu'il passait juste par là. Personne ne le croit vraiment.", - "image": "/static/img/cards/dream-arcade/rare/impostor_raccoon.webp" + "image": "/static/img/cards/dream-arcade/rare/impostor_raccoon.webp", + "expedition": { + "tags": [ + "personnage:raton-laveur", + "lieu:iles-jeux" + ] + } }, { "id": "lost-ruins-meerkat", "collectionId": "dream-arcade", "name": "Suricate des Ruines Oubliées", "description": "Lampe en main, la Suricate explore les temples oubliés des îles-jeux. Elle cherche moins le trésor que le plaisir de la découverte.", - "image": "/static/img/cards/dream-arcade/rare/lost_ruins_meerkat.webp" + "image": "/static/img/cards/dream-arcade/rare/lost_ruins_meerkat.webp", + "expedition": { + "tags": [ + "personnage:suricate", + "lieu:iles-jeux", + "theme:aventure", + "theme:tresor" + ] + } }, { "id": "whirlwind-ferret", "collectionId": "dream-arcade", "name": "Furet Tourbillon", "description": "Le Furet tourne sur lui-même comme une toupie et fait voler les caisses en bois. Quand il s'arrête, il reste toujours un fruit à ramasser.", - "image": "/static/img/cards/dream-arcade/rare/whirlwind_ferret.webp" + "image": "/static/img/cards/dream-arcade/rare/whirlwind_ferret.webp", + "expedition": { + "tags": [ + "personnage:furet", + "lieu:iles-jeux" + ] + } }, { "id": "red-tie-platypus", "collectionId": "dream-arcade", "name": "Ornithorynque à la Cravate Rouge", "description": "L'Ornithorynque a trouvé une cravate rouge sur une île de la jungle. Depuis, il ne la quitte plus et garde ses bananes dans un tonneau.", - "image": "/static/img/cards/dream-arcade/rare/red_tie_platypus.webp" + "image": "/static/img/cards/dream-arcade/rare/red_tie_platypus.webp", + "expedition": { + "tags": [ + "personnage:ornithorynque", + "lieu:iles-jeux" + ] + } }, { "id": "ink-splash-tree-frog", "collectionId": "dream-arcade", "name": "Rainette Barbouilleuse", "description": "Sur l'île des couleurs, la Rainette repeint tout en orange avec son rouleau. Le but du jeu ? Couvrir plus de sol que les autres avant la fin.", - "image": "/static/img/cards/dream-arcade/rare/ink_splash_tree_frog.webp" + "image": "/static/img/cards/dream-arcade/rare/ink_splash_tree_frog.webp", + "expedition": { + "tags": [ + "personnage:grenouille", + "lieu:iles-jeux" + ] + } }, { "id": "jellybean-alpaca", "collectionId": "dream-arcade", "name": "Alpaga en Costume de Dragée", "description": "L'Alpaga s'est déguisé en bonbon pour la grande course d'obstacles. Il tombe à chaque bosse, mais il se relève toujours en riant.", - "image": "/static/img/cards/dream-arcade/rare/jellybean_alpaca.webp" + "image": "/static/img/cards/dream-arcade/rare/jellybean_alpaca.webp", + "expedition": { + "tags": [ + "personnage:alpaga", + "lieu:iles-jeux" + ] + } }, { "id": "green-crystal-koala", "collectionId": "dream-arcade", "name": "Koala au Cristal Vert", "description": "Sur une île-jeu toute douce, le Koala mène une vie tranquille. Un cristal vert flotte au-dessus de sa tête : il dit qu'il est content.", - "image": "/static/img/cards/dream-arcade/rare/green_crystal_koala.webp" + "image": "/static/img/cards/dream-arcade/rare/green_crystal_koala.webp", + "expedition": { + "tags": [ + "personnage:koala", + "lieu:iles-jeux", + "objet:cristal" + ] + } }, { "id": "little-farm-duckling", "collectionId": "dream-arcade", "name": "Caneton de la Petite Ferme", "description": "Le Caneton s'occupe d'une petite ferme sur une île rêvée. Chaque matin, il arrose ses légumes avec un arrosoir presque aussi grand que lui.", - "image": "/static/img/cards/dream-arcade/rare/little_farm_duckling.webp" + "image": "/static/img/cards/dream-arcade/rare/little_farm_duckling.webp", + "expedition": { + "tags": [ + "personnage:caneton", + "lieu:iles-jeux", + "theme:jardin" + ] + } }, { "id": "steel-ball-hamster", "collectionId": "dream-arcade", "name": "Hamster Pilote de la Boule d'Acier", "description": "Le Hamster pilote une boule d'acier qui roule partout. Il ne va pas plus vite qu'à pied, mais il trouve ça beaucoup plus amusant.", - "image": "/static/img/cards/dream-arcade/rare/steel_ball_hamster.webp" + "image": "/static/img/cards/dream-arcade/rare/steel_ball_hamster.webp", + "expedition": { + "tags": [ + "personnage:hamster", + "lieu:iles-jeux" + ] + } }, { "id": "sprout-follower-dormouse", "collectionId": "dream-arcade", "name": "Loir et ses Petites Pousses", "description": "Le Loir s'est réveillé dans un jardin géant, suivi par de minuscules pousses de couleur. Elles l'aident à tout porter, même pendant ses siestes.", - "image": "/static/img/cards/dream-arcade/rare/sprout_follower_dormouse.webp" + "image": "/static/img/cards/dream-arcade/rare/sprout_follower_dormouse.webp", + "expedition": { + "tags": [ + "personnage:loir", + "lieu:iles-jeux", + "theme:jardin" + ] + } }, { "id": "rocket-penguin", "collectionId": "dream-arcade", "name": "Manchot Fusée", "description": "Sur l'île des dompteurs, quelqu'un a eu une drôle d'idée pour aller plus vite. Le Manchot ne dit rien, mais son regard en dit long.", - "image": "/static/img/cards/dream-arcade/rare/rocket_penguin.webp" + "image": "/static/img/cards/dream-arcade/rare/rocket_penguin.webp", + "expedition": { + "tags": [ + "personnage:manchot", + "lieu:iles-jeux" + ] + } }, { "id": "ghost-hunter-red-panda", "collectionId": "dream-arcade", "name": "Panda Roux Chasseur de Fantômes", "description": "Le Panda Roux enquête dans une maison hantée rêvée. Son détecteur s'affole, il fait froid, et il se demande pourquoi il a accepté de venir.", - "image": "/static/img/cards/dream-arcade/rare/ghost_hunter_red_panda.webp" + "image": "/static/img/cards/dream-arcade/rare/ghost_hunter_red_panda.webp", + "expedition": { + "tags": [ + "personnage:panda-roux", + "lieu:iles-jeux", + "theme:aventure", + "theme:nuit" + ] + } }, { "id": "rhythm-guitar-robin", "collectionId": "dream-arcade", "name": "Rouge-gorge à la Guitare Rythmique", "description": "Le Rouge-gorge appuie sur les boutons de couleur pile au bon moment. Il chante plus fort que sa guitare, et personne ne s'en plaint.", - "image": "/static/img/cards/dream-arcade/rare/rhythm_guitar_robin.webp" + "image": "/static/img/cards/dream-arcade/rare/rhythm_guitar_robin.webp", + "expedition": { + "tags": [ + "personnage:rouge-gorge", + "lieu:iles-jeux", + "theme:fete" + ] + } }, { "id": "monster-slayer-fox-cub", "collectionId": "dream-arcade", "name": "Renardeau Chasseur de Monstres", "description": "Le Renardeau chasse les monstres des îles-jeux avec ses deux épées. Avant chaque mission, il mange une pomme, l'air très sérieux.", - "image": "/static/img/cards/dream-arcade/rare/monster_slayer_fox_cub.webp" + "image": "/static/img/cards/dream-arcade/rare/monster_slayer_fox_cub.webp", + "expedition": { + "tags": [ + "personnage:renard", + "lieu:iles-jeux", + "theme:aventure", + "objet:arme" + ] + } }, { "id": "orange-armor-chinchilla", "collectionId": "dream-arcade", "name": "Chinchilla de l'Armure Orangée", "description": "Dans son armure orange, le Chinchilla explore les cavernes d'une île étrange. Ses grandes oreilles dépassent du casque, ce qui le gêne un peu.", - "image": "/static/img/cards/dream-arcade/rare/orange_armor_chinchilla.webp" + "image": "/static/img/cards/dream-arcade/rare/orange_armor_chinchilla.webp", + "expedition": { + "tags": [ + "personnage:chinchilla", + "lieu:iles-jeux", + "theme:aventure" + ] + } }, { "id": "golden-mystery-block", "collectionId": "dream-arcade", "name": "Bloc Mystère Doré", "description": "Frappé par en dessous, ce bloc doré lâche une pièce qui rebondit. Personne ne sait combien il en contient : peut-être une infinité.", - "image": "/static/img/cards/dream-arcade/common/golden_mystery_block.webp" + "image": "/static/img/cards/dream-arcade/common/golden_mystery_block.webp", + "expedition": { + "tags": [ + "lieu:iles-jeux", + "theme:tresor" + ] + } }, { "id": "golden-spotted-mushroom", "collectionId": "dream-arcade", "name": "Champignon Violet à Pois d'Or", "description": "Sur les îles-jeux, ce champignon violet à pois dorés fait grandir ceux qui le mangent. Les habitants le cueillent avec précaution.", - "image": "/static/img/cards/dream-arcade/common/golden_spotted_mushroom.webp" + "image": "/static/img/cards/dream-arcade/common/golden_spotted_mushroom.webp", + "expedition": { + "tags": [ + "lieu:iles-jeux", + "theme:jardin" + ] + } }, { "id": "crystal-hearts", "collectionId": "dream-arcade", "name": "Cœurs de Cristal", "description": "Trois cœurs de cristal dans les ruines. Plus ils sont pleins, plus on a de forces pour continuer l'aventure.", - "image": "/static/img/cards/dream-arcade/common/crystal_hearts.webp" + "image": "/static/img/cards/dream-arcade/common/crystal_hearts.webp", + "expedition": { + "tags": [ + "lieu:iles-jeux", + "objet:cristal", + "theme:aventure" + ] + } }, { "id": "ancient-pedestal-sword", "collectionId": "dream-arcade", "name": "Épée du Socle Ancien", "description": "Plantée dans son socle de pierre, cette épée a attendu très longtemps. Seul le Kitsune a réussi à la soulever.", - "image": "/static/img/cards/dream-arcade/common/ancient_pedestal_sword.webp" + "image": "/static/img/cards/dream-arcade/common/ancient_pedestal_sword.webp", + "expedition": { + "tags": [ + "lieu:iles-jeux", + "objet:arme", + "personnage:kitsune" + ] + } }, { "id": "clearing-chest", "collectionId": "dream-arcade", "name": "Coffre de la Clairière", "description": "Au milieu d'une clairière, un coffre entrouvert laisse voir une clé dorée. Elle ouvre sûrement une porte, quelque part sur l'île.", - "image": "/static/img/cards/dream-arcade/common/clearing_chest.webp" + "image": "/static/img/cards/dream-arcade/common/clearing_chest.webp", + "expedition": { + "tags": [ + "lieu:iles-jeux", + "theme:tresor" + ] + } }, { "id": "hilltop-golden-ring", "collectionId": "dream-arcade", "name": "Anneau Doré des Collines", "description": "Ces anneaux dorés flottent le long des chemins rapides. Le Loup les ramasse sans ralentir, et personne ne sait où il les range.", - "image": "/static/img/cards/dream-arcade/common/hilltop_golden_ring.webp" + "image": "/static/img/cards/dream-arcade/common/hilltop_golden_ring.webp", + "expedition": { + "tags": [ + "lieu:iles-jeux", + "personnage:loup", + "theme:tresor" + ] + } }, { "id": "rustling-tall-grass", "collectionId": "dream-arcade", "name": "Hautes Herbes Frémissantes", "description": "Les hautes herbes bougent toutes seules. Quelque chose s'y cache, mais quoi ? Il faut faire un pas de plus pour le savoir.", - "image": "/static/img/cards/dream-arcade/common/rustling_tall_grass.webp" + "image": "/static/img/cards/dream-arcade/common/rustling_tall_grass.webp", + "expedition": { + "tags": [ + "lieu:iles-jeux", + "theme:aventure" + ] + } }, { "id": "starry-capture-sphere", "collectionId": "dream-arcade", "name": "Sphère de Capture Étoilée", "description": "Une sphère violette et blanche ornée d'une étoile. On la lance pour inviter une créature à partir à l'aventure avec soi.", - "image": "/static/img/cards/dream-arcade/common/starry_capture_sphere.webp" + "image": "/static/img/cards/dream-arcade/common/starry_capture_sphere.webp", + "expedition": { + "tags": [ + "lieu:iles-jeux", + "theme:aventure", + "personnage:panda" + ] + } }, { "id": "cube-island", "collectionId": "dream-arcade", "name": "Île des Cubes", "description": "Une île entièrement faite de cubes : la terre, l'herbe, les arbres et même l'eau de la cascade. On peut tout démonter, puis tout reconstruire.", - "image": "/static/img/cards/dream-arcade/common/cube_island.webp" + "image": "/static/img/cards/dream-arcade/common/cube_island.webp", + "expedition": { + "tags": [ + "lieu:iles-jeux", + "personnage:pie" + ] + } }, { "id": "bell-bag", "collectionId": "dream-arcade", "name": "Sac de Clochettes", "description": "Sous l'arbre fruitier, un petit sac brodé d'une clochette. Sur l'île paisible du Capybara, c'est avec ça que l'on paie.", - "image": "/static/img/cards/dream-arcade/common/bell_bag.webp" + "image": "/static/img/cards/dream-arcade/common/bell_bag.webp", + "expedition": { + "tags": [ + "lieu:iles-jeux", + "personnage:capybara", + "theme:tresor" + ] + } }, { "id": "pearl-maze", "collectionId": "dream-arcade", "name": "Labyrinthe aux Perles", "description": "Un labyrinthe rempli de perles nacrées. Le Hérisson les mange toutes en une soirée, et le lendemain matin, elles sont revenues.", - "image": "/static/img/cards/dream-arcade/common/pearl_maze.webp" + "image": "/static/img/cards/dream-arcade/common/pearl_maze.webp", + "expedition": { + "tags": [ + "lieu:iles-jeux", + "personnage:herisson" + ] + } }, { "id": "falling-blocks", "collectionId": "dream-arcade", "name": "Pluie de Blocs", "description": "Les blocs de couleur tombent du ciel et s'emboîtent presque parfaitement. Il ne manque plus qu'une barre pour remplir la ligne.", - "image": "/static/img/cards/dream-arcade/common/falling_blocks.webp" + "image": "/static/img/cards/dream-arcade/common/falling_blocks.webp", + "expedition": { + "tags": [ + "lieu:iles-jeux", + "personnage:cameleon" + ] + } }, { "id": "vintage-controller", "collectionId": "dream-arcade", "name": "Manette d'Autrefois", "description": "Une vieille manette posée sur un coussin. On raconte que le Panda la tenait encore quand il s'est endormi, le soir du premier rêve de jeu.", - "image": "/static/img/cards/dream-arcade/common/vintage_controller.webp" + "image": "/static/img/cards/dream-arcade/common/vintage_controller.webp", + "expedition": { + "tags": [ + "lieu:iles-jeux", + "personnage:panda", + "theme:reves" + ] + } }, { "id": "island-arcade-cabinet", "collectionId": "dream-arcade", "name": "Borne d'Arcade de l'Île", "description": "Au sommet d'une petite île, une borne en bois attend les joueurs. Son écran change à chaque nouveau rêve du Panda.", - "image": "/static/img/cards/dream-arcade/common/island_arcade_cabinet.webp" + "image": "/static/img/cards/dream-arcade/common/island_arcade_cabinet.webp", + "expedition": { + "tags": [ + "lieu:iles-jeux", + "theme:reves" + ] + } }, { "id": "adventurer-potion", "collectionId": "dream-arcade", "name": "Potion de l'Aventurier", "description": "Une fiole rouge pour reprendre des forces, posée à côté d'une carte au trésor. Aucun aventurier des îles-jeux ne part sans elle.", - "image": "/static/img/cards/dream-arcade/common/adventurer_potion.webp" + "image": "/static/img/cards/dream-arcade/common/adventurer_potion.webp", + "expedition": { + "tags": [ + "lieu:iles-jeux", + "theme:aventure", + "objet:carte" + ] + } }, { "id": "save-crystal", "collectionId": "dream-arcade", "name": "Cristal de Sauvegarde", "description": "Ce grand cristal bleu flotte au-dessus de son socle. Les aventuriers le touchent avant de repartir, pour reprendre de là s'ils se perdent.", - "image": "/static/img/cards/dream-arcade/common/save_crystal.webp" + "image": "/static/img/cards/dream-arcade/common/save_crystal.webp", + "expedition": { + "tags": [ + "lieu:iles-jeux", + "objet:cristal", + "theme:aventure" + ] + } }, { "id": "rainbow-road", "collectionId": "dream-arcade", "name": "Route Arc-en-ciel", "description": "Une route arc-en-ciel serpente entre les îles, avec des virages en épingle. C'est le circuit préféré de la Loutre et de l'Écureuil.", - "image": "/static/img/cards/dream-arcade/common/rainbow_road.webp" + "image": "/static/img/cards/dream-arcade/common/rainbow_road.webp", + "expedition": { + "tags": [ + "lieu:iles-jeux", + "theme:voyage", + "personnage:loutre" + ] + } }, { "id": "camp-roast", "collectionId": "dream-arcade", "name": "Gigot du Campement", "description": "Après une longue chasse, rien ne vaut un gigot grillé au feu de camp. Le Fennec dit qu'il faut le retirer pile au bon moment.", - "image": "/static/img/cards/dream-arcade/common/camp_roast.webp" + "image": "/static/img/cards/dream-arcade/common/camp_roast.webp", + "expedition": { + "tags": [ + "lieu:iles-jeux", + "personnage:fennec", + "theme:aventure" + ] + } } ], "editions": [ diff --git a/website/public/data/site.json b/website/public/data/site.json index af6f389..97261cb 100644 --- a/website/public/data/site.json +++ b/website/public/data/site.json @@ -211,7 +211,85 @@ "dailyLost": "Pas trouvée aujourd’hui.", "dailyStreak": "Série : {streak}", "dailyAction": "Jouer", - "dailyResult": "Voir le résultat" + "dailyResult": "Voir le résultat", + "expeditionsKind": "Quête de longue durée", + "expeditionsTitle": "Expéditions", + "expeditionsDescription": "Envoyez vos cartes explorer l’archipel et rapportez des Éclats d’étoile.", + "expeditionsToLaunch": "De nouvelles destinations vous attendent.", + "expeditionsRunning": "En route, retour dans {time}.", + "expeditionsReturned": "Une expédition est de retour !", + "expeditionsIdle": "Expédition du jour lancée.", + "expeditionsNoCards": "Il faut {count} cartes rares ou mieux pour partir.", + "expeditionsClosed": "Les Expéditions sont fermées pour le moment.", + "expeditionsAction": "Préparer", + "expeditionsClaim": "Récupérer le butin", + "expeditionsOpen": "Voir" + }, + "expeditions": { + "eyebrow": "Quête de la Guilde", + "title": "Expéditions", + "intro": "Choisissez une destination du jour, composez une équipe et laissez-la explorer l’archipel pendant quelques heures.", + "back": "Retour à la Guilde", + "eclatsBalance": "{value} Éclats d’étoile", + "eclatsHelp": "Les Éclats d’étoile serviront bientôt à améliorer vos cartes.", + "closedTitle": "Les Expéditions sont fermées", + "closedText": "Les Veilleurs préparent les prochaines destinations. Revenez bientôt.", + "expired": "Les destinations du jour ont changé.", + "reload": "Recharger", + "activeTitle": "Vos expéditions", + "reportMeta": "{stars} · {hours} h", + "running": "En route, retour dans {time}.", + "returned": "De retour ! Le butin vous attend.", + "completed": "Butin récupéré.", + "cancelled": "Annulée par la Guilde : vos cartes sont libres.", + "claim": "Récupérer le butin", + "claimed": "Butin récupéré !", + "started": "Expédition lancée ! Revenez à son retour.", + "rewardEclats": "+{value} Éclats", + "rewardStardust": "+{value} d’étoiles", + "rewardPacks": "{count} paquet{s} offert{s}", + "limitReached": "Récupérez le butin de votre expédition avant d’en lancer une autre.", + "planTitle": "Préparer une expédition", + "nextDay": "Nouvelles destinations dans {time}.", + "noDestination": "Aucune destination n’est proposée aujourd’hui.", + "destinationsTitle": "1. Destination du jour", + "difficultyTitle": "2. Difficulté et durée", + "difficultyLabel": "Difficulté", + "durationLabel": "Durée", + "hours": "{hours} h", + "requirementsTitle": "Exigences de l’équipe", + "main": "principale", + "conditionTag": "Condition : une carte « {tag} » dans l’équipe, sinon le score baisse.", + "conditionCollection": "Condition : une carte de {collection} dans l’équipe, sinon le score baisse.", + "dangerText": "Danger, {label} : la {stat} baisse, sauf avec une carte « {tags} ».", + "or": " » ou « ", + "teamTitle": "3. Équipe", + "teamHelp": "Choisissez {count} cartes rares ou mieux. Chaque place double une stat de la carte qui l’occupe.", + "roleBadge": "{role} · {stat} ×2", + "slotEmpty": "Place libre", + "remove": "Retirer", + "cardsLabel": "Cartes disponibles", + "chooseCard": "Placer {card} en {role}", + "power": "Puissance {power}", + "busy": "En expédition", + "noRole": "Sans rôle", + "noCards": "Il vous faut au moins {count} cartes rares, épiques, légendaires ou mythiques.", + "previewTitle": "4. Aperçu", + "previewEmpty": "Choisissez une destination et {count} cartes pour voir le résultat attendu.", + "score": "Score {score} %", + "teamVersus": "{team} / {value}", + "limitedByStars": "Limité au score de {stars} ★", + "conditionMet": "Condition remplie.", + "conditionUnmet": "Condition non remplie : le score baisse.", + "dangerCountered": "{label} : paré.", + "dangerActive": "{label} : subi, la stat visée baisse.", + "durationMalus": "Expédition longue : l’Endurance de l’équipe ne suffit pas, toutes les stats baissent.", + "expected": "Butin attendu : environ {eclats} Éclats, {stardust} d’étoiles et {pack} % de chance de rapporter un paquet.", + "start": "Partir en expédition", + "tiers": { "struggle": "Retour difficile", "success": "Réussite", "triumph": "Triomphe" }, + "stats": { "bravoure": "Bravoure", "endurance": "Endurance", "fortune": "Fortune", "orientation": "Orientation" }, + "statShort": { "bravoure": "Bra", "endurance": "End", "fortune": "For", "orientation": "Ori" }, + "roles": { "bravoure": "Meneur", "endurance": "Gardien", "fortune": "Chercheur", "orientation": "Navigateur" } }, "daily": { "eyebrow": "Quête quotidienne", @@ -280,7 +358,8 @@ "redeemWhere": "Les cartes sont dans votre collection, les paquets dans « Paquets offerts ».", "giftTitle": "Paquets offerts", "giftDescription": "Ils s’ouvrent quand vous le souhaitez, sans utiliser vos ouvertures disponibles.", - "giftOpen": "Ouvrir" + "giftOpen": "Ouvrir", + "giftFromExpedition": "Rapporté d’expédition" } }, "library": { diff --git a/website/src/features/cards/CardDetailModal.jsx b/website/src/features/cards/CardDetailModal.jsx index 1e09917..1655e6c 100644 --- a/website/src/features/cards/CardDetailModal.jsx +++ b/website/src/features/cards/CardDetailModal.jsx @@ -11,6 +11,7 @@ export function CardDetailModal({ catalog, state, entry, runMutation, busy, onCl const spare = owned?.spare || 0; const value = state.shop.stardustValues[entry.edition.rarity] ?? 0; const favorites = new Set(state.favorites); + const expedition = state.expeditions?.busyEditions?.find((item) => item.editionId === entry.edition.id); return
@@ -23,6 +24,7 @@ export function CardDetailModal({ catalog, state, entry, runMutation, busy, onCl } + {expedition &&

En expédition jusqu’à {new Date(expedition.returnsAt).toLocaleString("fr-FR", { weekday: "long", hour: "2-digit", minute: "2-digit" })}.

} {quantity > 1 && !spare &&

Les doublons de cette carte sont réservés par une proposition d’échange en cours.

}
diff --git a/website/src/features/cards/CardsPage.jsx b/website/src/features/cards/CardsPage.jsx index 58982d4..48bfef5 100644 --- a/website/src/features/cards/CardsPage.jsx +++ b/website/src/features/cards/CardsPage.jsx @@ -9,6 +9,7 @@ import { CardsAccount, CardsDashboardLayout } from "./CardsDashboard.jsx"; import { CardsHomePanel } from "./CardsHomePanel.jsx"; import { CollectionPanel } from "./CollectionPanel.jsx"; import { DailyPanel } from "./DailyPanel.jsx"; +import { ExpeditionsPanel } from "./ExpeditionsPanel.jsx"; import { HistoryPanel } from "./HistoryPanel.jsx"; import { PackPanel } from "./PackPanel.jsx"; import { publishCardsReserve } from "./cardsReserve.js"; @@ -21,7 +22,7 @@ import { TransfersPanel } from "./TransfersPanel.jsx"; // Le jeu, puis l'économie et les échanges, puis le journal : mêmes groupes séparés par un filet que l'administration. const PLAYER_NAVIGATION = [["home", "guild", "packs", "collection"], ["shop", "transfers"], ["history", "account"]]; // Sections sans entrée de menu, ouvertes depuis une autre : le menu y désigne cette section parente. -const SUBSECTION_PARENTS = { daily: "guild" }; +const SUBSECTION_PARENTS = { daily: "guild", expeditions: "guild" }; const PLAYER_SECTIONS = new Set([...PLAYER_NAVIGATION.flat(), ...Object.keys(SUBSECTION_PARENTS)]); // Ancienne adresse conservée pour les favoris : le recyclage vit désormais dans la Collection. const PLAYER_SECTION_ALIASES = { recycling: "collection" }; @@ -274,6 +275,7 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", adminM {section === "home" && } {section === "guild" && } {section === "daily" && } + {section === "expeditions" && } {section === "packs" && } {section === "collection" && } {section === "shop" && } diff --git a/website/src/features/cards/ExpeditionPlanner.jsx b/website/src/features/cards/ExpeditionPlanner.jsx new file mode 100644 index 0000000..a052ab1 --- /dev/null +++ b/website/src/features/cards/ExpeditionPlanner.jsx @@ -0,0 +1,143 @@ +// Rôle : prépare une expédition solo : destination du jour, difficulté, durée, équipe par rôle et aperçu exact avant le départ. +import { useEffect, useMemo, useState } from "react"; +import { previewExpedition } from "./cardsApi.js"; +import { fillTemplate } from "./dailyShare.js"; +import { conditionText, coverEntry, dangerText, editionEntry, formatDecimal, formatEclats, STAT_IDS } from "./expeditionFormat.js"; +import { NebulaCard } from "./NebulaCard.jsx"; + +const PREVIEW_DELAY_MS = 250; +const TIER_VARIANTS = { struggle: "neutral", success: "success", triumph: "gold" }; + +function StatLine({ stats, content }) { + return {STAT_IDS.map((stat) => {content.statShort[stat]} {formatDecimal(stats[stat])})}; +} + +function Requirements({ catalog, option, content }) { + return
+

{content.requirementsTitle}

+
    {option.requirements.map((requirement) =>
  • + {content.stats[requirement.stat]}{requirement.main && {content.main}} + {requirement.value} +
  • )}
+ {option.condition &&

{conditionText(option.condition, catalog, content)}

} + {option.dangers.map((danger) =>

{dangerText(danger, catalog, content)}

)} +
; +} + +function Preview({ preview, content }) { + return
+
+ {content.tiers[preview.tier]} + {fillTemplate(content.score, { score: formatEclats(preview.scorePct) })} + {preview.limitedByStars && {fillTemplate(content.limitedByStars, { stars: preview.limitedByStars })}} +
+
    {preview.requirements.map((requirement) =>
  • = 100 || undefined}> + {content.stats[requirement.stat]}{fillTemplate(content.teamVersus, { team: formatDecimal(requirement.team), value: requirement.value })} +
  • )}
+ {preview.conditionMet != null &&

{preview.conditionMet ? content.conditionMet : content.conditionUnmet}

} + {preview.dangers.map((danger) =>

{fillTemplate(danger.countered ? content.dangerCountered : content.dangerActive, { label: danger.label })}

)} + {preview.durationFactor < 1 &&

{content.durationMalus}

} +

{fillTemplate(content.expected, { eclats: formatEclats(preview.expected.eclats), stardust: formatEclats(preview.expected.stardust), pack: formatEclats(preview.expected.packChancePct) })}

+
; +} + +export function ExpeditionPlanner({ catalog, view, content, busy, onStart }) { + const [destinationId, setDestinationId] = useState(view.destinations[0]?.id || ""); + const [stars, setStars] = useState(view.stars.min); + const [hours, setHours] = useState(view.durations[0]); + const [slots, setSlots] = useState(() => Array.from({ length: view.soloCards }, () => null)); + const [activeSlot, setActiveSlot] = useState(0); + const [preview, setPreview] = useState({ key: "", value: null, error: "" }); + const destination = view.destinations.find((item) => item.id === destinationId) || view.destinations[0]; + const option = destination?.stars[stars]; + const complete = Boolean(destination && slots.every(Boolean)); + const body = useMemo(() => ({ day: view.day, destinationId: destination?.id, difficulty: stars, durationHours: hours, slots }), [view.day, destination?.id, stars, hours, slots]); + const bodyKey = JSON.stringify(body); + + // Aperçu demandé au serveur dès que l'équipe est complète, après une courte pause pour ne pas l'interroger à chaque clic. + useEffect(() => { + if (!complete) return undefined; + let active = true; + const timer = setTimeout(() => { + previewExpedition(JSON.parse(bodyKey)) + .then((result) => { if (active) setPreview({ key: bodyKey, value: result.preview, error: "" }); }) + .catch((error) => { if (active) setPreview({ key: bodyKey, value: null, error: error.message }); }); + }, PREVIEW_DELAY_MS); + return () => { active = false; clearTimeout(timer); }; + }, [bodyKey, complete]); + + const roleStat = destination?.roles[activeSlot]; + const cards = useMemo(() => [...view.cards].sort((a, b) => Number(a.busy) - Number(b.busy) || (b.stats[roleStat] ?? 0) - (a.stats[roleStat] ?? 0) || b.power - a.power), [view.cards, roleStat]); + if (!destination) return

{content.noDestination}

; + + function choose(card) { + const next = slots.map((editionId, index) => (index !== activeSlot && editionId && editionEntry(catalog, editionId)?.card.id === card.cardId ? null : editionId)); + next[activeSlot] = card.editionId; + setSlots(next); + const empty = next.findIndex((editionId) => !editionId); + if (empty >= 0) setActiveSlot(empty); + } + + const shownPreview = complete && preview.key === bodyKey ? preview : null; + return
+
+

{content.destinationsTitle}

+
{view.destinations.map((item) => { + const cover = item.coverCardId && coverEntry(catalog, item.coverCardId); + return ; + })}
+
+ +
+

{content.difficultyTitle}

+
+
{Object.keys(destination.stars).map(Number).map((value) => )}
+
{view.durations.map((value) => )}
+
+ {option && } +
+ +
+

{content.teamTitle}

+

{fillTemplate(content.teamHelp, { count: view.soloCards })}

+
{slots.map((editionId, index) => { + const entry = editionId && editionEntry(catalog, editionId); + const stat = destination.roles[index]; + return
+ + {entry ? entry.card.name : content.slotEmpty} + {entry && } +
; + })}
+ {cards.length ?
    {cards.map((card) => { + const entry = editionEntry(catalog, card.editionId); + if (!entry) return null; + const selected = slots.includes(card.editionId); + return
  • + choose(card)} selectLabel={fillTemplate(content.chooseCard, { card: entry.card.name, role: content.roles[roleStat] })} /> + {card.busy ? content.busy : fillTemplate(content.power, { power: card.power })} + +
  • ; + })}
:

{fillTemplate(content.noCards, { count: view.soloCards })}

} +
+ +
+

{content.previewTitle}

+ {!complete &&

{fillTemplate(content.previewEmpty, { count: view.soloCards })}

} + {shownPreview?.error &&

{shownPreview.error}

} + {shownPreview?.value && } +
+ +
+
+
; +} diff --git a/website/src/features/cards/ExpeditionReport.jsx b/website/src/features/cards/ExpeditionReport.jsx new file mode 100644 index 0000000..b96b402 --- /dev/null +++ b/website/src/features/cards/ExpeditionReport.jsx @@ -0,0 +1,45 @@ +// Rôle : présente une expédition du joueur : en route (compte à rebours), revenue (butin à récupérer), terminée ou annulée. +import { fillTemplate, formatCountdown } from "./dailyShare.js"; +import { coverEntry, editionEntry, formatEclats } from "./expeditionFormat.js"; +import { NebulaCard } from "./NebulaCard.jsx"; +import { formatStardust } from "./stardustFormat.js"; + +const TIER_VARIANTS = { struggle: "neutral", success: "success", triumph: "gold" }; + +function RewardBadges({ reward, content }) { + return
+ {fillTemplate(content.rewardEclats, { value: formatEclats(reward.eclats) })} + {reward.stardust > 0 && {fillTemplate(content.rewardStardust, { value: formatStardust(reward.stardust) })}} + {reward.packs.length > 0 && {fillTemplate(content.rewardPacks, { count: reward.packs.length, s: reward.packs.length > 1 ? "s" : "" })}} +
; +} + +export function ExpeditionReport({ catalog, expedition, content, now, busy, onClaim }) { + // Le serveur dit « en route » au chargement ; passé l'heure du retour, la page propose déjà de récupérer le butin. + const status = expedition.status === "running" && expedition.returnsAt <= now ? "returned" : expedition.status; + const cover = expedition.destination.coverCardId && coverEntry(catalog, expedition.destination.coverCardId); + const stars = "★".repeat(expedition.stars); + return
+ {cover && } +
+

{fillTemplate(content.reportMeta, { stars, hours: expedition.hours })}

+

{expedition.destination.name}

+ {status === "running" &&

{fillTemplate(content.running, { time: formatCountdown(expedition.returnsAt - now) })}

} + {status === "returned" &&

{content.returned}

} + {status === "completed" &&

{content.completed}

} + {status === "cancelled" &&

{content.cancelled}

} + {expedition.result &&
+ {content.tiers[expedition.result.tier]} + {fillTemplate(content.score, { score: formatEclats(expedition.result.scorePct) })} +
} + {expedition.reward && } +
    {expedition.slots.filter((slot) => slot.editionId).map((slot) => { + const entry = editionEntry(catalog, slot.editionId); + return entry &&
  • {slot.role ? content.roles[slot.role] : content.noRole}
  • ; + })}
+ {status === "returned" && !expedition.claimedAt &&
+ +
} +
+
; +} diff --git a/website/src/features/cards/ExpeditionsPanel.jsx b/website/src/features/cards/ExpeditionsPanel.jsx new file mode 100644 index 0000000..82958d2 --- /dev/null +++ b/website/src/features/cards/ExpeditionsPanel.jsx @@ -0,0 +1,90 @@ +// Rôle : présente les Expéditions, quête de la Guilde : expéditions du joueur (retour, butin) et préparation d'une expédition solo. +import { useEffect, useState } from "react"; +import { claimExpedition, loadExpeditions, startExpedition } from "./cardsApi.js"; +import { fillTemplate, formatCountdown } from "./dailyShare.js"; +import { ExpeditionPlanner } from "./ExpeditionPlanner.jsx"; +import { ExpeditionReport } from "./ExpeditionReport.jsx"; +import { formatEclats } from "./expeditionFormat.js"; + +const COUNTDOWN_TICK_MS = 30_000; + +// Les refus propres aux Expéditions restent dans ce panneau ; runMutation garde le reste (réseau, session). +const expeditionCall = (call) => async () => { + try { + return await call(); + } catch (error) { + if (String(error.code || "").startsWith("EXPEDITION")) return { expeditionError: error }; + throw error; + } +}; + +export function ExpeditionsPanel({ catalog, state, runMutation, busy, content }) { + const [view, setView] = useState(null); + const [loadError, setLoadError] = useState(""); + const [reloadKey, setReloadKey] = useState(0); + const [notice, setNotice] = useState(null); + const [now, setNow] = useState(() => Date.now()); + + useEffect(() => { + let active = true; + loadExpeditions() + .then((result) => { if (active) { setView(result); setLoadError(""); setNow(Date.now()); } }) + .catch((error) => { if (active) setLoadError(error.message); }); + return () => { active = false; }; + }, [reloadKey]); + + useEffect(() => { + const timer = setInterval(() => setNow(Date.now()), COUNTDOWN_TICK_MS); + return () => clearInterval(timer); + }, []); + + if (loadError) return

{content.title}

{loadError}

; + if (!view) return

{content.title}

; + + const reload = () => { setNotice(null); setReloadKey((key) => key + 1); }; + const handle = (result, success) => { + if (result?.expeditions) { + setView(result.expeditions); + setNow(Date.now()); + setNotice(success ? { variant: "success", text: success } : null); + return true; + } + if (result?.expeditionError?.code === "EXPEDITION_DAY_EXPIRED") setNow(view.nextDayAt); + else if (result?.expeditionError) setNotice({ variant: "warning", text: result.expeditionError.message }); + return false; + }; + const start = async (body) => handle(await runMutation(expeditionCall(() => startExpedition(body))), content.started); + const claim = async (id) => handle(await runMutation(expeditionCall(() => claimExpedition(id))), content.claimed); + + const expired = view.enabled && now >= view.nextDayAt; + const active = view.expeditions.filter((expedition) => expedition.status === "running" && !expedition.claimedAt); + const limitReached = active.length >= view.soloLimit; + + return
+
+

{content.eyebrow}

{content.title}

{content.intro}

+
+ {fillTemplate(content.eclatsBalance, { value: formatEclats(state.wallet.eclats ?? 0) })} + {content.back} +
+
+

{content.eclatsHelp}

+ {notice &&

{notice.text}

} + {expired &&
{content.expired}
} + + {view.expeditions.length > 0 &&
+

{content.activeTitle}

+
{view.expeditions.map((expedition) => )}
+
} + + {!view.enabled ?

{content.closedTitle}

{content.closedText}

+ : limitReached ?

{content.limitReached}

+ : !expired && <> +
+

{content.planTitle}

+ {fillTemplate(content.nextDay, { time: formatCountdown(view.nextDayAt - now) })} +
+ + } +
; +} diff --git a/website/src/features/cards/GuildPanel.jsx b/website/src/features/cards/GuildPanel.jsx index 3cbac42..50d0cd5 100644 --- a/website/src/features/cards/GuildPanel.jsx +++ b/website/src/features/cards/GuildPanel.jsx @@ -1,5 +1,7 @@ // Rôle : présente la Guilde des Veilleurs et la tuile de chacune de ses quêtes, avec leur état. +import { useState } from "react"; import { dailyQuestStatus, fillTemplate, formatStreak } from "./dailyShare.js"; +import { expeditionQuestStatus } from "./expeditionFormat.js"; import { guildQuests } from "./guildQuests.js"; // Carte du jour : un dos vierge, propre à aucune collection et marqué d'un « ? », figure la carte cachée à retrouver. @@ -28,18 +30,41 @@ function DailyQuest({ summary: daily, content }) { ; } +// Expéditions : la couverture montre le Grand Vide, et le bouton mène au butin dès qu'une expédition est revenue. +const EXPEDITIONS_COVER = "/static/img/cards/primordial-nebula/epic/deep_sky_ray.webp"; + +function ExpeditionsQuest({ summary, pending, content, now }) { + const returned = summary.returned > 0 || (summary.nextReturnAt != null && summary.nextReturnAt <= now); + return ; +} + // Tuile de chaque type de quête, choisie par l'identifiant donné dans guildQuests. -const QUEST_TILES = { daily: DailyQuest }; +const QUEST_TILES = { daily: DailyQuest, expeditions: ExpeditionsQuest }; export function GuildPanel({ catalog, state, content }) { - const quests = guildQuests(state).filter((quest) => QUEST_TILES[quest.id]); + // Heure d'affichage de la page : elle suffit pour savoir si une expédition est déjà rentrée. + const [now] = useState(() => Date.now()); + const quests = guildQuests(state, now).filter((quest) => QUEST_TILES[quest.id]); return

{content.eyebrow}

{content.title}

{content.intro}

- {quests.length ?
{quests.map(({ id, summary }) => { + {quests.length ?
{quests.map(({ id, summary, pending }) => { const Tile = QUEST_TILES[id]; - return ; + return ; })}
:

{content.empty}

}
; diff --git a/website/src/features/cards/HistoryPanel.jsx b/website/src/features/cards/HistoryPanel.jsx index c5431fa..1d001bd 100644 --- a/website/src/features/cards/HistoryPanel.jsx +++ b/website/src/features/cards/HistoryPanel.jsx @@ -16,7 +16,9 @@ const EVENT_LABELS = { gift_pack_opened: "Paquet offert ouvert", cards_recycled: "Doublons recyclés", opening_purchased: "Ouverture achetée", - daily_won: "Carte du jour trouvée" + daily_won: "Carte du jour trouvée", + expedition_completed: "Expédition terminée", + expedition_cancelled_by_guild: "Expédition annulée par la Guilde" }; // Le journal garde la quantité réellement offerte : les comptes plus anciens n'ont reçu qu'une ouverture. @@ -52,6 +54,12 @@ function HistoryDetail({ entry, catalog }) { if (details.sent || details.received) return {[details.sent && `Donnée : ${cardReference(details.sent, catalog)}`, details.received && `Reçue : ${cardReference(details.received, catalog)}`].filter(Boolean).join(" · ")}; if (entry.type === "cards_recycled") return {details.count} exemplaire{details.count > 1 ? "s" : ""} · +{formatStardust(details.stardust)} d’étoiles; if (entry.type === "daily_won") return {`Défi n° ${details.number} · ${details.guesses}/6`}{details.stardust > 0 && ` · +${formatStardust(details.stardust)} d’étoiles`}; + if (entry.type === "expedition_completed") { + const tier = { struggle: "Retour difficile", success: "Réussite", triumph: "Triomphe" }[details.tier]; + const gains = [`+${details.eclats} Éclats`, details.stardust > 0 && `+${formatStardust(details.stardust)} d’étoiles`, details.packs > 0 && `${details.packs} paquet${details.packs > 1 ? "s" : ""} offert${details.packs > 1 ? "s" : ""}`].filter(Boolean); + return {[`${details.destinationName} · ${"★".repeat(details.difficulty)} · ${details.hours} h`, tier, ...gains].filter(Boolean).join(" · ")}; + } + if (entry.type === "expedition_cancelled_by_guild") return {details.destinationName} · cartes libérées, sans butin; if (entry.type === "opening_purchased") return −{formatStardust(details.price)} d’étoiles; if (!details.collectionId) return null; const name = catalog.collections.find((item) => item.id === details.collectionId)?.name; diff --git a/website/src/features/cards/PackPanel.jsx b/website/src/features/cards/PackPanel.jsx index 92abe65..6ff7e14 100644 --- a/website/src/features/cards/PackPanel.jsx +++ b/website/src/features/cards/PackPanel.jsx @@ -71,10 +71,10 @@ export function PackPanel({ catalog, state, runMutation, busy, content, reserveC
{giftPacks.map((gift) => { const collection = catalog.collections.find((item) => item.id === gift.collectionId); const details = packDetails(gift.options, catalog); - return ; diff --git a/website/src/features/cards/admin/AdminGuild.jsx b/website/src/features/cards/admin/AdminGuild.jsx index 212ff34..b72e928 100644 --- a/website/src/features/cards/admin/AdminGuild.jsx +++ b/website/src/features/cards/admin/AdminGuild.jsx @@ -2,6 +2,7 @@ import { useState } from "react"; import { ApplyActions } from "./adminSettingForm.jsx"; import { inRange, MAX_VALUE, parse, shopSettingSaver } from "./adminSettings.js"; +import { ExpeditionSettings } from "./ExpeditionSettings.jsx"; // Carte du jour : la partie du jour (joueurs et gagnants), puis la récompense d'une victoire. function DailyQuestSettings({ setting, daily, busy, save }) { @@ -31,7 +32,10 @@ export function AdminGuild({ dashboard, busy, runMutation, refreshDashboard }) { const save = shopSettingSaver(setting, runMutation, refreshDashboard); return
{setting - ? + ? <> + + {dashboard.expeditionSettings && } + :

Chargement des quêtes…

}
; } diff --git a/website/src/features/cards/admin/AdminHistory.jsx b/website/src/features/cards/admin/AdminHistory.jsx index 0d10601..7ebb3f5 100644 --- a/website/src/features/cards/admin/AdminHistory.jsx +++ b/website/src/features/cards/admin/AdminHistory.jsx @@ -3,6 +3,7 @@ import { useEffect, useState } from "react"; import { loadAdminHistory } from "../cardsApi.js"; import { summarizeReward } from "../rewardText.js"; import { DATE_FORMATTER, formatDuration } from "./adminFormat.js"; +import { expeditionSettingLabel, formatSettingValue } from "./expeditionSettingFields.js"; const EVENT_LABELS = { recharge_updated: "Recharge modifiée", @@ -15,7 +16,9 @@ const EVENT_LABELS = { campaign_created: "Campagne créée", campaign_revoked: "Campagne révoquée", campaign_extended: "Campagne prolongée", - account_deleted: "Compte joueur supprimé" + account_deleted: "Compte joueur supprimé", + expedition_settings_updated: "Expéditions modifiées", + expedition_cancelled: "Expédition annulée" }; const collectionName = (entry, catalog) => catalog.collections.find((item) => item.id === entry.entityId)?.name || entry.entityId; @@ -51,6 +54,8 @@ function eventDetail(entry, catalog) { case "campaign_created": return `${campaignName || entry.entityId} · ${summarizeReward(details.reward, catalog)}`; case "campaign_extended": return `${campaignName || entry.entityId} · ${details.expiresAt == null ? "sans expiration" : `jusqu’au ${DATE_FORMATTER.format(details.expiresAt)}`}`; case "campaign_revoked": return campaignName || entry.entityId; + case "expedition_settings_updated": return (details.changes || []).map((item) => change(expeditionSettingLabel(item.path), formatSettingValue(item.previous), formatSettingValue(item.next))).filter(Boolean).join(" · "); + case "expedition_cancelled": return details.destinationId; default: return ""; } } diff --git a/website/src/features/cards/admin/ExpeditionSettings.jsx b/website/src/features/cards/admin/ExpeditionSettings.jsx new file mode 100644 index 0000000..41df1a4 --- /dev/null +++ b/website/src/features/cards/admin/ExpeditionSettings.jsx @@ -0,0 +1,128 @@ +// Rôle : règle les Expéditions depuis Administration › Guilde : un panneau par groupe de réglages, les destinations, et le suivi du jour. +import { useState } from "react"; +import { ConfirmModal } from "../../../components/ToolboxModals.jsx"; +import { cancelExpedition, updateExpeditionSettings } from "../cardsApi.js"; +import { DATE_FORMATTER } from "./adminFormat.js"; +import { ApplyActions } from "./adminSettingForm.jsx"; +import { inRange, parse } from "./adminSettings.js"; +import { EXPEDITION_SETTING_GROUPS } from "./expeditionSettingFields.js"; + +const readPath = (source, path) => path.split(".").reduce((value, key) => value?.[key], source); + +function writePath(target, path, value) { + const keys = path.split("."); + keys.slice(0, -1).reduce((node, key) => node[key], target)[keys.at(-1)] = value; +} + +const toDraft = (value) => (typeof value === "boolean" ? value : Array.isArray(value) ? value.map(String) : String(value)); +const fromDraft = (value) => (typeof value === "boolean" ? value : Array.isArray(value) ? value.map(parse) : parse(value)); +const validValue = (field, value) => (field.kind === "bool" ? typeof value === "boolean" : (Array.isArray(value) ? value : [value]).every((item) => inRange(item, field.min, field.max))); + +// Un panneau : brouillon de ses réglages, vérifiés avec les bornes du serveur ; les contraintes entre réglages sont vérifiées par le serveur. +function SettingsGroup({ group, settings, schema, busy, save }) { + const fields = group.fields.map((field) => ({ ...field, ...schema.find((item) => item.path === field.path) })); + const initial = () => Object.fromEntries(fields.map((field) => [field.path, toDraft(readPath(settings, field.path))])); + const [draft, setDraft] = useState(initial); + const values = Object.fromEntries(fields.map((field) => [field.path, fromDraft(draft[field.path])])); + const invalid = fields.filter((field) => !validValue(field, values[field.path])); + const changed = !invalid.length && fields.some((field) => JSON.stringify(values[field.path]) !== JSON.stringify(readPath(settings, field.path))); + const set = (path, value) => setDraft((current) => ({ ...current, [path]: value })); + return
+

{group.title}

+

{group.help}

+
{fields.map((field) => { + const value = draft[field.path]; + if (field.kind === "bool") return
+ {field.label} + +
; + if (Array.isArray(value)) return
+ {field.label} +
{value.map((item, index) => )}
+
; + return ; + })}
+ {invalid.length > 0 &&

{invalid.map((field) => `${field.label} : entier de ${field.min.toLocaleString("fr-FR")} à ${field.max.toLocaleString("fr-FR")}`).join(" · ")}

} + setDraft(initial())} + onApply={() => save((next) => fields.forEach((field) => writePath(next, field.path, values[field.path])))} + confirmTitle={`Appliquer les réglages « ${group.title} » ?`} + confirmMessage="Les nouveaux réglages s’appliquent aux prochains départs. Les expéditions en route gardent ceux de leur départ." + /> +
; +} + +// Destinations : proposées ou non, et poids dans le tirage du jour. Leurs textes vivent dans le fichier du serveur. +function DestinationSettings({ settings, destinations, busy, save }) { + const initial = () => Object.fromEntries(destinations.map((destination) => [destination.id, { active: settings.destinations[destination.id].active, weight: String(settings.destinations[destination.id].weight) }])); + const [draft, setDraft] = useState(initial); + const invalid = destinations.filter((destination) => !inRange(parse(draft[destination.id].weight), 0, 100)); + const changed = !invalid.length && destinations.some((destination) => draft[destination.id].active !== settings.destinations[destination.id].active || parse(draft[destination.id].weight) !== settings.destinations[destination.id].weight); + const set = (id, changes) => setDraft((current) => ({ ...current, [id]: { ...current[id], ...changes } })); + return
+

Destinations

+

Une destination retirée n’est plus tirée ; le poids règle sa fréquence parmi les destinations proposées. Les destinations cachées ne sont jamais tirées.

+
    {destinations.map((destination) =>
  • + {destination.name}{destination.hidden && Cachée} + + +
  • )}
+ {invalid.length > 0 &&

Poids : entier de 0 à 100.

} + setDraft(initial())} + onApply={() => save((next) => destinations.forEach((destination) => { next.destinations[destination.id] = { active: draft[destination.id].active, weight: parse(draft[destination.id].weight) }; }))} + confirmTitle="Appliquer les destinations ?" + confirmMessage="Le changement vaut pour les prochains tirages : les destinations déjà proposées aujourd’hui restent jusqu’à minuit." + /> +
; +} + +function ExpeditionsToday({ today, destinations, busy, onCancel }) { + const [cancelling, setCancelling] = useState(null); + const name = (id) => destinations.find((destination) => destination.id === id)?.name || id; + return
+

Aujourd’hui

+

{today.launches} départ{today.launches > 1 ? "s" : ""} · {today.running} en route · {today.returnedUnclaimed} butin{today.returnedUnclaimed > 1 ? "s" : ""} à récupérer.

+ {today.runningList.length > 0 &&
    {today.runningList.map((expedition) =>
  • + {name(expedition.destinationId)} · {"★".repeat(expedition.stars)} + {expedition.creatorName} · retour le {DATE_FORMATTER.format(expedition.returnsAt)} + +
  • )}
} + {cancelling && { + const target = cancelling; + setCancelling(null); + if (confirmed) await onCancel(target.id); + }} + />} +
; +} + +export function ExpeditionSettings({ dashboard, busy, runMutation, refreshDashboard }) { + const { settings, schema, destinations, updatedAt } = dashboard.expeditionSettings; + const save = async (apply) => { + const next = structuredClone(settings); + apply(next); + if (await runMutation(() => updateExpeditionSettings(next))) await refreshDashboard(); + }; + const cancel = async (id) => { + if (await runMutation(() => cancelExpedition(id))) await refreshDashboard(); + }; + return
+

Expéditions

+ + {EXPEDITION_SETTING_GROUPS.map((group) => )} + +
; +} diff --git a/website/src/features/cards/admin/expeditionSettingFields.js b/website/src/features/cards/admin/expeditionSettingFields.js new file mode 100644 index 0000000..3a6cb1c --- /dev/null +++ b/website/src/features/cards/admin/expeditionSettingFields.js @@ -0,0 +1,99 @@ +// Rôle : libellés et regroupement des réglages des Expéditions pour l'administration et son historique. +// Les bornes viennent du schéma du serveur (tableau de bord) ; un test vérifie que chaque réglage du schéma a ici son libellé. + +const STARS = ["1 ★", "2 ★", "3 ★", "4 ★", "5 ★"]; +const STATS_IN_ORDER = ["principale", "2e stat", "3e stat", "4e stat"]; + +export const EXPEDITION_SETTING_GROUPS = [ + { + id: "general", + title: "Général", + help: "Ouverture, destinations proposées chaque jour, durées et règles du solo.", + fields: [ + { path: "enabled", label: "Expéditions ouvertes aux joueurs" }, + { path: "day.destinationsPerDay", label: "Destinations proposées par jour" }, + { path: "day.avoidRepeatDays", label: "Jours avant qu’une destination revienne" }, + { path: "durations.hours", label: "Durées proposées (heures)", items: ["Courte", "Moyenne", "Longue"] }, + { path: "solo.cards", label: "Cartes en solo" }, + { path: "solo.maxConcurrent", label: "Expéditions solo en même temps" }, + { path: "solo.minStars", label: "Étoile minimale en solo" }, + { path: "solo.maxStars", label: "Étoile maximale en solo" } + ] + }, + { + id: "power", + title: "Puissance et rôles", + help: "Puissance de base de chaque rareté, gain par niveau et plafond commun ; multiplicateur du rôle d’une place.", + fields: [ + { path: "power.rare", label: "Puissance de base d’une rare" }, + { path: "power.epic", label: "Puissance de base d’une épique" }, + { path: "power.legendary", label: "Puissance de base d’une légendaire" }, + { path: "power.mythic", label: "Puissance de base d’une mythique" }, + { path: "power.perLevel", label: "Gain de Puissance par niveau" }, + { path: "power.cap", label: "Plafond de Puissance" }, + { path: "roles.multiplierPct", label: "Multiplicateur du rôle (%)" } + ] + }, + { + id: "requirements", + title: "Exigences", + help: "Exigence d’une stat par place : elle est multipliée par le nombre de places, plus les places dont le rôle double cette stat.", + fields: [ + ...STARS.map((stars, index) => ({ path: `requirements.star${index + 1}`, label: `Exigences par place en ${stars}`, items: STATS_IN_ORDER })), + { path: "requirements.conditionMissPct", label: "Baisse du score si la condition de 3 ★ manque (%)" } + ] + }, + { + id: "score", + title: "Score, durée et dangers", + help: "Paliers, rendement au-delà de 100 %, malus des longues expéditions et des dangers, et ce que l’Endurance en efface.", + fields: [ + { path: "score.successPct", label: "Seuil de Réussite (%)" }, + { path: "score.triumphPct", label: "Seuil de Triomphe (%)" }, + { path: "score.capPct", label: "Plafond du score (%)" }, + { path: "score.mainWeight", label: "Poids de la stat principale" }, + { path: "score.otherWeight", label: "Poids des autres stats" }, + { path: "score.overflowPct", label: "Valeur d’un point au-delà de 100 % (%)" }, + { path: "score.overflowSpanPct", label: "Dépassement pris en compte (%)" }, + { path: "durations.malusPct", label: "Malus de durée (%)", items: ["Courte", "Moyenne", "Longue"] }, + { path: "durations.endurancePerSlot", label: "Endurance par place qui efface le malus de durée" }, + { path: "danger.malusPct", label: "Malus d’un danger (%)" }, + { path: "danger.shieldMaxPct", label: "Part du malus que l’Endurance peut effacer (%)" }, + { path: "danger.endurancePerSlot", label: "Endurance par place pour le bouclier complet" } + ] + }, + { + id: "loot", + title: "Butin", + help: "Butin par heure (proportionnel à la durée choisie), multiplié par la difficulté et le palier ; la Fortune n’améliore que la chance de paquet.", + fields: [ + { path: "loot.eclatsPerHourCents", label: "Éclats par heure (en centièmes : 200 = 2)" }, + { path: "loot.stardustPerHourCents", label: "Poussière par heure (en centièmes : 25 = 0,25)" }, + { path: "loot.packPerHourPermille", label: "Chance de paquet par heure (‰)" }, + { path: "loot.maxPacks", label: "Paquets au plus par expédition" }, + { path: "loot.difficultyPct", label: "Multiplicateur de difficulté (%)", items: STARS }, + { path: "loot.tierPct", label: "Multiplicateur du palier (%)", items: ["Retour difficile", "Réussite", "Triomphe"] }, + { path: "loot.fortunePerPointPct", label: "Bonus de paquet par point de Fortune par place (%)" }, + { path: "loot.fortuneCapPct", label: "Bonus de Fortune maximal (%)" }, + { path: "loot.bonusSlotPct", label: "Multiplicateur des destinations bonus (%)", items: ["5e destination", "6e destination"] } + ] + } +]; + +const LABELS = new Map(EXPEDITION_SETTING_GROUPS.flatMap((group) => group.fields.map((field) => [field.path, field.label]))); + +// Libellé d'un réglage dans l'historique ; une destination se nomme par son nom. +export function expeditionSettingLabel(path, destinations = []) { + const destination = path.match(/^destinations\.([^.]+)\.(active|weight)$/); + if (destination) { + const name = destinations.find((item) => item.id === destination[1])?.name || destination[1]; + return `${name} · ${destination[2] === "active" ? "proposée" : "poids"}`; + } + return LABELS.get(path) || path; +} + +export function formatSettingValue(value) { + if (typeof value === "boolean") return value ? "oui" : "non"; + if (Array.isArray(value)) return value.join(" / "); + return value ?? "—"; +} diff --git a/website/src/features/cards/cardsApi.js b/website/src/features/cards/cardsApi.js index 9b76dc6..665f538 100644 --- a/website/src/features/cards/cardsApi.js +++ b/website/src/features/cards/cardsApi.js @@ -166,3 +166,28 @@ export function loadCampaignDetail(campaignId) { export function extendCampaign(campaignId, expiresAt) { return request(`/admin/campaigns/${encodeURIComponent(campaignId)}/expiry`, { method: "PUT", body: JSON.stringify({ expiresAt }) }); } + +export function loadExpeditions() { + return request("/expeditions"); +} + +// Aperçu exact d'une équipe : le palier ne dépend d'aucun tirage, seul le butin est arrondi au hasard au départ. +export function previewExpedition(body) { + return request("/expeditions/preview", { method: "POST", body: JSON.stringify(body) }); +} + +export function startExpedition(body) { + return request("/expeditions", { method: "POST", headers: { "Idempotency-Key": crypto.randomUUID() }, body: JSON.stringify(body) }); +} + +export function claimExpedition(expeditionId) { + return request(`/expeditions/${encodeURIComponent(expeditionId)}/claim`, { method: "POST" }); +} + +export function updateExpeditionSettings(settings) { + return request("/admin/expeditions/settings", { method: "PUT", body: JSON.stringify({ settings }) }); +} + +export function cancelExpedition(expeditionId) { + return request(`/admin/expeditions/${encodeURIComponent(expeditionId)}/cancel`, { method: "POST" }); +} diff --git a/website/src/features/cards/expeditionFormat.js b/website/src/features/cards/expeditionFormat.js new file mode 100644 index 0000000..6b66195 --- /dev/null +++ b/website/src/features/cards/expeditionFormat.js @@ -0,0 +1,44 @@ +// Rôle : règles d'affichage des Expéditions Sokko TCG (libellés des stats, rôles et paliers, conditions, statut de la tuile de Guilde). +import { fillTemplate, formatCountdown } from "./dailyShare.js"; + +export const STAT_IDS = ["bravoure", "endurance", "fortune", "orientation"]; + +export const formatEclats = (value) => Number(value).toLocaleString("fr-FR", { maximumFractionDigits: 1 }); +export const formatDecimal = (value) => Number(value).toLocaleString("fr-FR", { maximumFractionDigits: 1 }); + +export function tagLabel(catalog, tagId) { + return catalog.expeditionTags?.find((tag) => tag.id === tagId)?.label || tagId; +} + +// Condition de 3 ★ : une carte qui porte une étiquette, ou une carte d'une collection. +export function conditionText(condition, catalog, content) { + if (!condition) return ""; + if (condition.type === "collection") return fillTemplate(content.conditionCollection, { collection: catalog.collections.find((item) => item.id === condition.collectionId)?.name || condition.collectionId }); + return fillTemplate(content.conditionTag, { tag: tagLabel(catalog, condition.tag) }); +} + +export function dangerText(danger, catalog, content) { + return fillTemplate(content.dangerText, { label: danger.label, stat: content.stats[danger.stat], tags: danger.unlessTags.map((tag) => tagLabel(catalog, tag)).join(content.or) }); +} + +// Statut de la tuile Expéditions dans la Guilde (textes cards.guild). +export function expeditionQuestStatus(summary, content, now = Date.now()) { + if (!summary.enabled && !summary.running && !summary.returned) return content.expeditionsClosed; + if (summary.returned > 0 || (summary.nextReturnAt != null && summary.nextReturnAt <= now)) return content.expeditionsReturned; + if (summary.running) return fillTemplate(content.expeditionsRunning, { time: formatCountdown(summary.nextReturnAt - now) }); + if (summary.eligible < summary.soloCards) return fillTemplate(content.expeditionsNoCards, { count: summary.soloCards }); + return summary.launchedToday ? content.expeditionsIdle : content.expeditionsToLaunch; +} + +// Édition de référence d'une carte (la standard), pour illustrer une destination. +export function coverEntry(catalog, cardId) { + const card = catalog.cards.find((item) => item.id === cardId); + const edition = catalog.editions.find((item) => item.cardId === cardId && item.rarity !== "mythic" && !item.promotional); + return card && edition ? { editionId: edition.id, edition, card } : null; +} + +export function editionEntry(catalog, editionId) { + const edition = catalog.editions.find((item) => item.id === editionId); + const card = edition && catalog.cards.find((item) => item.id === edition.cardId); + return card ? { editionId, edition, card } : null; +} diff --git a/website/src/features/cards/guildQuests.js b/website/src/features/cards/guildQuests.js index 8775317..5ac6d67 100644 --- a/website/src/features/cards/guildQuests.js +++ b/website/src/features/cards/guildQuests.js @@ -1,10 +1,21 @@ // Rôle : recense les quêtes que la Guilde des Veilleurs propose au joueur et celles qui l'attendent. -// La Carte du jour est la première ; chaque nouvelle quête (Expéditions…) s'ajoute à cette liste avec sa tuile dans GuildPanel. +// Chaque quête (Carte du jour, Expéditions…) s'ajoute à cette liste avec sa tuile dans GuildPanel. -// Une quête : identifiant (qui choisit sa tuile), état du jour fourni par le serveur et `pending` tant qu'elle attend le joueur. -export function guildQuests(state) { +// Expéditions en attente : un butin à récupérer, ou aucune expédition lancée aujourd'hui alors que le joueur a de quoi partir. +// Au plus un rappel par jour, plus les retours ; un joueur sans cartes jouables n'est jamais sollicité. +export function expeditionsPending(summary, now = Date.now()) { + if (!summary) return false; + if (summary.returned > 0 || (summary.nextReturnAt != null && summary.nextReturnAt <= now)) return true; + return summary.enabled && !summary.running && !summary.launchedToday && summary.eligible >= summary.soloCards; +} + +// Une quête : identifiant (qui choisit sa tuile), état fourni par le serveur et `pending` tant qu'elle attend le joueur. +// Les Expéditions n'apparaissent que si elles sont ouvertes, ou tant qu'une expédition du joueur n'est pas terminée. +export function guildQuests(state, now = Date.now()) { const quests = []; if (state.daily) quests.push({ id: "daily", pending: state.daily.status === "playing", summary: state.daily }); + const expeditions = state.expeditions; + if (expeditions && (expeditions.enabled || expeditions.running || expeditions.returned)) quests.push({ id: "expeditions", pending: expeditionsPending(expeditions, now), summary: expeditions }); return quests; } diff --git a/website/src/styles/_nebula-expeditions.scss b/website/src/styles/_nebula-expeditions.scss new file mode 100644 index 0000000..884aca8 --- /dev/null +++ b/website/src/styles/_nebula-expeditions.scss @@ -0,0 +1,79 @@ +// Rôle : met en page les Expéditions de Sokko TCG (expéditions du joueur, destinations du jour, équipe par rôle, aperçu). +// Les composants restent ceux du design system (nds-panel, nds-card, nds-button, nds-badge, nds-inline-notice) ; ce fichier ne règle que la disposition. + +.nebula-expeditions { display: grid; gap: var(--space-4); min-width: 0; } +.nebula-expeditions .nds-section-heading.nebula-section-heading { margin-bottom: 0; } +.nebula-expeditions > .nebula-form-help { margin: 0; } +.nebula-expeditions > .nds-inline-notice { margin: 0; } +.nebula-expeditions h3, .nebula-expeditions h4 { margin: 0; } + +// Expéditions du joueur : une carte par expédition, couverture de la destination, équipe et butin. +.nebula-expedition-active { display: grid; gap: var(--space-3); } +.nebula-expedition-reports { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 340px), 1fr)); gap: var(--space-4); } +.nds-card.nebula-expedition-report { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: var(--space-4); align-items: start; padding: var(--space-4); } +.nds-card-cover.nebula-expedition-report-cover { width: 88px; overflow: hidden; aspect-ratio: 1; border-radius: var(--radius-md); } +.nebula-expedition-report-cover img { display: block; width: 100%; height: 100%; object-fit: cover; } +.nds-card-body.nebula-expedition-report-body { display: grid; gap: var(--space-2); justify-items: start; min-width: 0; padding: 0; } +.nebula-expedition-report-body p { margin: 0; } +.nebula-expedition-report-status { color: var(--color-text-primary); font-weight: 700; } +.nebula-expedition-report-body .nds-card-actions { padding: 0; } +.nebula-expedition-report-team { display: flex; flex-wrap: wrap; gap: var(--space-3); margin: 0; padding: 0; list-style: none; } +.nebula-expedition-report-team li { display: grid; gap: var(--space-1); justify-items: center; color: var(--color-text-secondary); font-size: var(--font-size-xs); } +.nebula-expedition-rewards { display: flex; flex-wrap: wrap; gap: var(--space-2); } + +// Préparation : quatre étapes empilées. +.nebula-expedition-plan-heading { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: var(--space-2) var(--space-4); } +.nebula-expedition-planner { display: grid; gap: var(--space-4); } +.nds-panel.nebula-expedition-step { display: grid; gap: var(--space-3); padding: var(--space-5); } +.nebula-expedition-step > .nebula-form-help, .nebula-expedition-step > .nds-inline-notice { margin: 0; } + +.nebula-expedition-destinations { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 280px), 1fr)); gap: var(--space-3); } +.nebula-expedition-destination { display: grid; grid-template-columns: 72px minmax(0, 1fr); gap: var(--space-3); align-items: start; padding: var(--space-3); border: 1px solid var(--color-border); border-radius: var(--radius-md); background: var(--color-bg-surface-alt); color: inherit; font: inherit; text-align: left; cursor: pointer; transition: border-color 160ms var(--ease-standard), background 160ms var(--ease-standard); } +.nebula-expedition-destination:hover { background: var(--color-bg-hover); } +.nebula-expedition-destination[aria-pressed="true"] { border-color: rgba(246, 196, 83, 0.54); background: rgba(246, 196, 83, 0.12); } +.nebula-expedition-destination img { width: 72px; aspect-ratio: 1; border-radius: var(--radius-sm); object-fit: cover; } +.nebula-expedition-destination-copy { display: grid; gap: var(--space-1); min-width: 0; } +.nebula-expedition-destination-copy > span:not(.nebula-expedition-destination-roles) { color: var(--color-text-secondary); font-size: var(--font-size-sm); text-wrap: pretty; } +.nebula-expedition-destination-roles { display: flex; flex-wrap: wrap; gap: var(--space-1); margin-top: var(--space-1); } + +.nebula-expedition-choices { display: flex; flex-wrap: wrap; gap: var(--space-3); } +.nebula-expedition-requirements { display: grid; gap: var(--space-2); } +.nebula-expedition-requirements ul, .nebula-expedition-checks { display: grid; gap: var(--space-1); margin: 0; padding: 0; list-style: none; } +.nebula-expedition-requirements li, .nebula-expedition-checks li { display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); padding: var(--space-2) var(--space-3); border-radius: var(--radius-sm); background: var(--color-bg-surface-alt); } +.nebula-expedition-requirements li > span { display: inline-flex; align-items: center; gap: var(--space-2); } +.nebula-expedition-requirements p { margin: 0; color: var(--color-text-secondary); font-size: var(--font-size-sm); } +.nebula-expedition-checks li[data-met] strong { color: var(--color-success); } + +// Équipe : une place par rôle, puis les cartes jouables, triées pour la place choisie. +.nebula-expedition-slots { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 280px), 1fr)); gap: var(--space-3); } +.nebula-expedition-slot { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2) var(--space-3); padding: var(--space-3); border: 1px solid var(--color-border); border-radius: var(--radius-md); } +.nebula-expedition-slot[data-active] { border-color: rgba(246, 196, 83, 0.54); } +.nebula-expedition-slot > span { flex: 1 1 120px; min-width: 0; color: var(--color-text-secondary); font-size: var(--font-size-sm); } +.nebula-expedition-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(132px, 1fr)); gap: var(--space-4) var(--space-3); max-height: 640px; margin: 0; padding: var(--space-1); overflow-y: auto; list-style: none; } +.nebula-expedition-cards li { display: grid; gap: var(--space-1); justify-items: center; text-align: center; } +.nebula-expedition-cards li[data-busy] { opacity: 0.55; } +.nebula-expedition-card-power { color: var(--color-text-primary); font-size: var(--font-size-xs); font-weight: 700; } +.nebula-expedition-stats { display: flex; flex-wrap: wrap; justify-content: center; gap: var(--space-1) var(--space-2); color: var(--color-text-muted); font-size: var(--font-size-xs); } + +.nebula-expedition-preview { display: grid; gap: var(--space-3); } +.nebula-expedition-preview .nds-inline-notice { margin: 0; } +.nebula-expedition-expected { margin: 0; color: var(--color-text-primary); } + +// Administration › Guilde : un panneau par groupe de réglages, des champs alignés en grille. +.nebula-admin-expeditions { display: grid; gap: var(--space-4); } +.nebula-admin-expeditions > h2 { margin: var(--space-4) 0 0; } +.nebula-admin-expedition-group > .nebula-form-help { margin: 0; } +.nebula-admin-expedition-fields { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 260px), 1fr)); gap: var(--space-3) var(--space-4); } +.nebula-admin-expedition-field { display: grid; gap: var(--space-1); align-content: start; min-width: 0; margin: 0; padding: 0; border: 0; } +.nebula-admin-expedition-field > span, .nebula-admin-expedition-field > legend { color: var(--color-text-secondary); font-size: var(--font-size-sm); } +.nebula-admin-expedition-field > legend { margin-bottom: var(--space-1); padding: 0; } +.nebula-admin-expedition-field > .nds-button { justify-self: start; } +.nebula-admin-expedition-items { display: flex; flex-wrap: wrap; gap: var(--space-2); } +.nebula-admin-expedition-items label { display: grid; flex: 1 1 72px; gap: 2px; min-width: 64px; color: var(--color-text-muted); font-size: var(--font-size-xs); } +.nebula-admin-expedition-destinations { display: grid; gap: var(--space-2); margin: 0; padding: 0; list-style: none; } +.nebula-admin-expedition-destinations .nds-list-row { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2) var(--space-4); padding: var(--space-3); } +.nebula-admin-expedition-destinations .nds-list-row > strong { display: inline-flex; flex: 1 1 200px; align-items: center; gap: var(--space-2); } +.nebula-admin-expedition-destinations .nds-list-row > span { flex: 1 1 200px; color: var(--color-text-secondary); font-size: var(--font-size-sm); } +.nebula-admin-expedition-destinations label { display: inline-flex; align-items: center; gap: var(--space-2); color: var(--color-text-secondary); font-size: var(--font-size-sm); } +.nebula-admin-expedition-destinations input { width: 80px; } +.nebula-admin-expedition-destinations .nds-list-row > .nds-button { flex: 0 0 auto; width: auto; } diff --git a/website/src/styles/main.scss b/website/src/styles/main.scss index 6c887c9..d057384 100644 --- a/website/src/styles/main.scss +++ b/website/src/styles/main.scss @@ -14,6 +14,7 @@ @use "diablo4"; @use "aniimo"; @use "nebula-cards"; +@use "nebula-expeditions"; @use "games/checklist"; @use "design-system/attributes"; @use "responsive";