The 669 // comments sitting right above a function, method or hook become /** */ blocks, unchanged in wording; eslint directives stay right above the line they target. website/AGENTS.md now asks for JSDoc on function comments and // inside function bodies. ExpeditionPlanner.jsx grew past 300 lines and gets its full header, as the header test requires. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
217 lines
14 KiB
JavaScript
217 lines
14 KiB
JavaScript
/**
|
||
* @file Objets des Expéditions de Sokko TCG : inventaire, ancre (rappel), destinations bonus (étoile guide,
|
||
* carte céleste, carte au trésor), Rose des vents (nouvelles destinations du jour), gravure d'une
|
||
* étiquette sur un équipement et atelier des communes à pouvoir.
|
||
*
|
||
* Contexte : méthodes d'ExpeditionService, ajoutées à son prototype par `Object.assign` en fin
|
||
* d'expedition-service.js ; `this` est l'instance d'ExpeditionService.
|
||
* Points d'entrée : `itemsOf`, `addBonusDestination`, `rerollDestinations`, `recallExpedition`, `engrave`, `craft`.
|
||
* Utilisé par : api.js (par `service.expeditions`) ; `addItemsInTx` par le retour d'une expédition.
|
||
* Dépend de : expedition-rules.js (identifiants des objets, tirage du jour, bonus).
|
||
* Attention : suffixe `InTx` = à appeler dans une transaction déjà ouverte ; `forgetItemsInTx` sert à la
|
||
* suppression de compte.
|
||
* @see docs/expeditions/equilibrage.md
|
||
*/
|
||
|
||
import { dailyDayKey } from "./daily.js";
|
||
import { bonusLootPct, bonusSlotLevel, drawExpeditionDay, ITEM_IDS, starsForLevel } from "./expedition-rules.js";
|
||
|
||
function fail(status, code, message) {
|
||
throw Object.assign(new Error(message), { status, code });
|
||
}
|
||
|
||
// Objet consommé pour chaque destination bonus, et place de la destination dans la journée du joueur.
|
||
const BONUS_ITEMS = Object.freeze({ guideStar: "5", skyChart: "6", fragment: "hidden" });
|
||
|
||
export const itemMethods = {
|
||
/**
|
||
* Destinations que chaque objet ajouterait aujourd'hui, pour les proposer sous les destinations du jour : l'objet, le nombre
|
||
* d'exemplaires qu'il faut, si sa place est déjà prise, et les étoiles et le butin (en %) de la destination ajoutée.
|
||
*/
|
||
bonusOffers(entries, settings) {
|
||
const dailyHighest = Math.max(0, ...entries.filter((entry) => !entry.bonusSlot).map((entry) => entry.level ?? 0));
|
||
const used = new Set(entries.map((entry) => entry.bonusSlot).filter(Boolean).map(String));
|
||
return Object.entries(BONUS_ITEMS).map(([item, slot]) => ({
|
||
item, slot, used: used.has(slot), required: item === "fragment" ? settings.items.fragmentsForMap : 1,
|
||
stars: starsForLevel(bonusSlotLevel(slot, settings, dailyHighest), settings), lootPct: bonusLootPct(slot, settings)
|
||
}));
|
||
},
|
||
|
||
itemsOf(playerId) {
|
||
const items = Object.fromEntries(ITEM_IDS.map((id) => [id, 0]));
|
||
for (const row of this.db.prepare("SELECT item_id, quantity FROM player_items WHERE player_id = ?").all(playerId)) items[row.item_id] = row.quantity;
|
||
return items;
|
||
},
|
||
|
||
addItemsInTx(playerId, itemIds) {
|
||
const add = this.db.prepare(`INSERT INTO player_items(player_id, item_id, quantity) VALUES (?, ?, 1)
|
||
ON CONFLICT(player_id, item_id) DO UPDATE SET quantity = quantity + 1`);
|
||
for (const itemId of itemIds) add.run(playerId, itemId);
|
||
},
|
||
|
||
consumeItemInTx(playerId, itemId, count = 1) {
|
||
const used = this.db.prepare("UPDATE player_items SET quantity = quantity - ? WHERE player_id = ? AND item_id = ? AND quantity >= ?").run(count, playerId, itemId, count);
|
||
if (!used.changes) fail(409, "NOT_ENOUGH_ITEMS", "Vous n’avez pas assez de cet objet.");
|
||
if (this.cards.isDevAccount(playerId)) this.ensureDevItemsInTx(playerId);
|
||
},
|
||
|
||
/**
|
||
* Compte de développement : au moins un exemplaire de chaque objet, et assez de fragments pour une carte au trésor, pour tout
|
||
* essayer ; complété à chaque chargement et après chaque usage.
|
||
*/
|
||
ensureDevItemsInTx(playerId) {
|
||
const fill = this.db.prepare(`INSERT INTO player_items(player_id, item_id, quantity) VALUES (?, ?, ?)
|
||
ON CONFLICT(player_id, item_id) DO UPDATE SET quantity = MAX(quantity, excluded.quantity)`);
|
||
for (const itemId of ITEM_IDS) fill.run(playerId, itemId, itemId === "fragment" ? this.settings.items.fragmentsForMap : 1);
|
||
},
|
||
|
||
/**
|
||
* Destinations bonus du joueur pour un jour (Étoile guide, Carte céleste, cachée), avec leur première condition et leurs deux
|
||
* premiers dangers. Niveau : selon le plus haut de ses destinations du jour (`daily`), voir `bonusSlotLevel`.
|
||
*/
|
||
bonusEntries(playerId, day, settings, daily = this.ensureDay(playerId, day, settings)) {
|
||
const dailyHighest = Math.max(0, ...daily.map((entry) => entry.level));
|
||
return this.db.prepare("SELECT slot, destination_id FROM player_bonus_destinations WHERE player_id = ? AND day = ? ORDER BY slot").all(playerId, day).map((row) => {
|
||
const destination = this.destinations.find((item) => item.id === row.destination_id);
|
||
const level = bonusSlotLevel(row.slot, settings, dailyHighest);
|
||
return destination && { destination, entry: { condition: destination.conditions[0], dangers: destination.dangers.slice(0, 2) }, bonusSlot: row.slot, level };
|
||
}).filter(Boolean);
|
||
},
|
||
|
||
/**
|
||
* Destinations jouables du joueur : celles du jour, puis ses destinations bonus. À appeler dans une transaction.
|
||
* Une destination déjà ajoutée en bonus ne revient pas dans la liste du jour (après une Rose des vents, par exemple).
|
||
*/
|
||
playerEntries(playerId, day, settings) {
|
||
const daily = this.ensureDay(playerId, day, settings);
|
||
const bonus = this.bonusEntries(playerId, day, settings, daily);
|
||
const bonusIds = new Set(bonus.map((entry) => entry.destination.id));
|
||
return [...daily.filter((entry) => !bonusIds.has(entry.destination.id)), ...bonus];
|
||
},
|
||
|
||
/** Ajoute une destination bonus à la journée du joueur, en consommant l'objet correspondant (4 fragments pour une carte au trésor). */
|
||
addBonusDestination(playerId, { item } = {}) {
|
||
const settings = this.settings;
|
||
const slot = BONUS_ITEMS[item];
|
||
if (!slot) fail(400, "ITEM_INVALID", "Cet objet n’ouvre pas de destination.");
|
||
this.cards.database.transaction(() => {
|
||
if (!settings.enabled) fail(409, "EXPEDITIONS_CLOSED", "Les Expéditions sont fermées pour le moment.");
|
||
const day = dailyDayKey(this.now());
|
||
const taken = this.playerEntries(playerId, day, settings);
|
||
if (taken.some((entry) => entry.bonusSlot === slot)) fail(409, "BONUS_ALREADY_USED", "Vous avez déjà ajouté cette destination aujourd’hui.");
|
||
const takenIds = new Set(taken.map((entry) => entry.destination.id));
|
||
const pool = this.destinations.filter((destination) => (slot === "hidden" ? destination.hidden : !destination.hidden && settings.destinations[destination.id]?.active !== false) && !takenIds.has(destination.id));
|
||
if (!pool.length) fail(409, "BONUS_UNAVAILABLE", "Aucune autre destination n’est disponible aujourd’hui.");
|
||
this.consumeItemInTx(playerId, item, item === "fragment" ? settings.items.fragmentsForMap : 1);
|
||
const destination = pool[this.random(pool.length)];
|
||
this.db.prepare("INSERT INTO player_bonus_destinations(player_id, day, slot, destination_id, created_at) VALUES (?, ?, ?, ?, ?)").run(playerId, day, slot, destination.id, this.now());
|
||
this.cards.audit(playerId, "item_used", item, { item, destinationId: destination.id, destinationName: destination.name });
|
||
});
|
||
return { expeditions: this.getExpeditions(playerId), state: this.cards.getState(playerId) };
|
||
},
|
||
|
||
/**
|
||
* Rose des vents : retire les destinations du jour du joueur (et leurs niveaux) parmi celles qu'il a débloquées, en évitant celles
|
||
* qu'il vient d'avoir et ses destinations bonus, puis celles des jours récents, quand il en reste assez. Sans limite par jour : une
|
||
* Rose par tirage ; ses destinations bonus restent, et ses expéditions ou groupes déjà lancés ne changent pas.
|
||
*/
|
||
rerollDestinations(playerId) {
|
||
const settings = this.settings;
|
||
this.cards.database.transaction(() => {
|
||
if (!settings.enabled) fail(409, "EXPEDITIONS_CLOSED", "Les Expéditions sont fermées pour le moment.");
|
||
const day = dailyDayKey(this.now());
|
||
const daily = this.ensureDay(playerId, day, settings);
|
||
const current = [...daily, ...this.bonusEntries(playerId, day, settings, daily)].map((entry) => entry.destination.id);
|
||
this.consumeItemInTx(playerId, "windRose");
|
||
const unlocked = this.unlockedDestinationIds(playerId);
|
||
const proposed = this.proposedDestinationIds(unlocked, settings);
|
||
const fresh = (avoid) => proposed.filter((id) => !avoid.includes(id)).length >= Math.min(settings.day.destinationsPerDay, proposed.length);
|
||
const withRecent = [...current, ...this.recentDestinationIds(playerId, day, settings)];
|
||
const draw = drawExpeditionDay(this.destinations, settings, fresh(withRecent) ? withRecent : current, (max) => this.random(max), unlocked);
|
||
this.db.prepare("UPDATE player_expedition_days SET draw_json = ?, rerolled_at = ? WHERE player_id = ? AND day = ?").run(JSON.stringify(draw), this.now(), playerId, day);
|
||
this.cards.audit(playerId, "item_used", "windRose", { item: "windRose", destinationIds: draw.map((entry) => entry.destinationId) });
|
||
});
|
||
return { expeditions: this.getExpeditions(playerId), state: this.cards.getState(playerId) };
|
||
},
|
||
|
||
/** Ancre : une expédition solo en route revient tout de suite, avec la part de butin déjà gagnée (Éclats et poussière au prorata). */
|
||
recallExpedition(playerId, expeditionId) {
|
||
this.cards.database.transaction(() => {
|
||
const row = this.db.prepare(`SELECT e.*, m.reward_json FROM expeditions e JOIN expedition_members m ON m.expedition_id = e.id AND m.player_id = ?
|
||
WHERE e.id = ? AND m.claimed_at IS NULL`).get(playerId, expeditionId);
|
||
if (!row || row.status !== "running") fail(404, "EXPEDITION_NOT_FOUND", "Cette expédition n’est pas en route.");
|
||
if (row.mode !== "solo") fail(409, "RECALL_SOLO_ONLY", "Seule une expédition solo peut être rappelée.");
|
||
const now = this.now();
|
||
if (row.returns_at <= now) fail(409, "EXPEDITION_RETURNED", "Cette expédition est déjà rentrée.");
|
||
this.consumeItemInTx(playerId, "anchor");
|
||
const share = Math.max(0, Math.min(1, (now - row.departs_at) / (row.returns_at - row.departs_at)));
|
||
const reward = JSON.parse(row.reward_json);
|
||
const kept = { eclats: Math.floor(reward.eclats * share), stardust: Math.floor(reward.stardust * share), packs: [], items: [], recalledPct: Math.round(share * 100) };
|
||
this.db.prepare("UPDATE expedition_members SET reward_json = ? WHERE expedition_id = ? AND player_id = ?").run(JSON.stringify(kept), row.id, playerId);
|
||
this.db.prepare("UPDATE expeditions SET returns_at = ? WHERE id = ?").run(now, row.id);
|
||
const setup = JSON.parse(row.setup_json);
|
||
this.cards.audit(playerId, "item_used", "anchor", { item: "anchor", destinationId: setup.destination.id, destinationName: setup.destination.name, recalledPct: kept.recalledPct });
|
||
});
|
||
return { expedition: this.expeditionView(expeditionId, playerId), expeditions: this.getExpeditions(playerId), state: this.cards.getState(playerId) };
|
||
},
|
||
|
||
engravingsOf(playerId) {
|
||
return new Map(this.db.prepare("SELECT edition_id, tag FROM equipment_engravings WHERE player_id = ?").all(playerId).map((row) => [row.edition_id, row.tag]));
|
||
},
|
||
|
||
/** Burin : grave une étiquette du vocabulaire sur une commune, une seule fois, pour créer la synergie qu'on veut. */
|
||
engrave(playerId, { editionId, tag } = {}) {
|
||
this.cards.database.transaction(() => {
|
||
const item = this.equipmentItem(editionId);
|
||
if (!item) fail(400, "EQUIPMENT_INVALID", "Seules les communes se gravent.");
|
||
if (!this.cards.quantityOf(playerId, editionId)) fail(404, "CARD_NOT_OWNED", "Vous ne possédez pas cette commune.");
|
||
if (!this.cards.catalog.expeditionTags.some((entry) => entry.id === tag) || item.tags.includes(tag)) fail(400, "ENGRAVING_INVALID", "Choisissez une étiquette que cette commune ne porte pas encore.");
|
||
if (this.db.prepare("SELECT 1 FROM equipment_engravings WHERE player_id = ? AND edition_id = ?").get(playerId, editionId)) fail(409, "ENGRAVING_EXISTS", "Cette commune est déjà gravée.");
|
||
this.consumeItemInTx(playerId, "engraving");
|
||
this.db.prepare("INSERT INTO equipment_engravings(player_id, edition_id, tag, engraved_at) VALUES (?, ?, ?, ?)").run(playerId, editionId, tag, this.now());
|
||
this.cards.audit(playerId, "item_used", "engraving", { item: "engraving", editionId, tag });
|
||
});
|
||
return this.cards.getState(playerId);
|
||
},
|
||
|
||
/** Communes de pouvoir que l'atelier peut fabriquer : celles des collections des Expéditions déjà illustrées. */
|
||
powerCommons() {
|
||
const expeditionCollections = new Set(this.cards.catalog.collections.filter((collection) => collection.packCategory === "expedition").map((collection) => collection.id));
|
||
return this.cards.catalog.editions.filter((edition) => {
|
||
const card = this.cards.index.cards.get(edition.cardId);
|
||
return card?.image && card.expedition?.equipment?.power && !edition.promotional && expeditionCollections.has(card.collectionId);
|
||
});
|
||
},
|
||
|
||
atelierAvailable() {
|
||
return this.powerCommons().length > 0;
|
||
},
|
||
|
||
/** Atelier : un plan et 3 doublons de communes donnent une commune de pouvoir des Carnets, au hasard. */
|
||
craft(playerId, { editionIds } = {}) {
|
||
if (!Array.isArray(editionIds) || editionIds.length !== 3) fail(400, "ATELIER_INVALID", "Choisissez 3 doublons de communes.");
|
||
let crafted;
|
||
this.cards.database.transaction(() => {
|
||
const recipes = this.powerCommons();
|
||
if (!recipes.length) fail(409, "ATELIER_UNAVAILABLE", "L’atelier attend encore les illustrations des Carnets des Veilleurs.");
|
||
if (this.db.prepare("SELECT 1 FROM openings WHERE player_id = ? AND status = 'pending'").get(playerId)) fail(409, "PENDING_OPENING", "Terminez d'abord l'ouverture en cours.");
|
||
const needed = new Map();
|
||
for (const editionId of editionIds) needed.set(editionId, (needed.get(editionId) || 0) + 1);
|
||
const owned = new Map(this.cards.collectionOf(playerId).map((entry) => [entry.editionId, entry]));
|
||
for (const [editionId, count] of needed) {
|
||
if (!this.equipmentItem(editionId)) fail(400, "ATELIER_INVALID", "L’atelier n’utilise que des communes.");
|
||
if ((owned.get(editionId)?.spare ?? 0) < count) fail(409, "NOT_A_DUPLICATE", "Il faut des doublons libres de ces communes.");
|
||
}
|
||
this.consumeItemInTx(playerId, "plan");
|
||
for (const [editionId, count] of needed) this.cards.removeDuplicates(playerId, editionId, count);
|
||
crafted = recipes[this.random(recipes.length)].id;
|
||
this.cards.addCard(playerId, crafted);
|
||
this.cards.audit(playerId, "item_used", "plan", { item: "plan", editionId: crafted, used: editionIds });
|
||
});
|
||
return { crafted, state: this.cards.getState(playerId) };
|
||
},
|
||
|
||
forgetItemsInTx(playerId) {
|
||
for (const table of ["player_items", "equipment_engravings", "player_bonus_destinations"]) this.db.prepare(`DELETE FROM ${table} WHERE player_id = ?`).run(playerId);
|
||
}
|
||
};
|