sokko-g/services/cards/expedition-items.js
Shinuwa 17a87a889a Add the Rose des vents to draw new daily destinations once a day
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:52:48 +01:00

178 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Rôle : objets des Expéditions Sokko TCG : inventaire, ancre (rappel), destinations bonus (étoile guide, carte céleste, carte au trésor),
// Rose des vents (nouvelles destinations du jour) et gravure d'une étiquette sur un équipement. Ces méthodes s'ajoutent à ExpeditionService (Object.assign sur son prototype).
import { dailyDayKey } from "./daily.js";
import { bonusLevel, drawExpeditionDay, ITEM_IDS, levelCount } 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 = {
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.");
},
// Destinations bonus du joueur pour un jour : 5e, 6e ou cachée, avec leur première condition et leurs deux premiers dangers.
// Niveau : le plus haut pour la destination cachée, stable mais au hasard pour la 5e et la 6e.
bonusEntries(playerId, day, settings) {
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 = row.slot === "hidden" ? levelCount(settings) - 1 : bonusLevel(`${playerId}:${day}:${row.slot}:${row.destination_id}`, settings);
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 bonus = this.bonusEntries(playerId, day, settings);
const bonusIds = new Set(bonus.map((entry) => entry.destination.id));
return [...this.ensureDay(playerId, day, settings).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. Une fois par jour ; 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 current = [...this.ensureDay(playerId, day, settings), ...this.bonusEntries(playerId, day, settings)].map((entry) => entry.destination.id);
if (this.db.prepare("SELECT rerolled_at FROM player_expedition_days WHERE player_id = ? AND day = ?").get(playerId, day)?.rerolled_at != null) {
fail(409, "REROLL_ALREADY_USED", "Vous avez déjà changé vos destinations aujourd’hui.");
}
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) };
},
rerolledToday(playerId, day) {
return this.db.prepare("SELECT rerolled_at FROM player_expedition_days WHERE player_id = ? AND day = ?").get(playerId, day)?.rerolled_at != null;
},
// 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);
}
};