sokko-g/services/cards/expedition-items.js
Shinuwa 30413de036 Rework the expedition screens: in-place return, illustrated bag and workshop, card sheet tabs and an engraving workshop
Expeditions
- The journey keeps the destination landscape still while a sky scenery
  (clouds, floating isles, shards, sparkles) drifts behind the cards.
- A returned expedition shows only what the player receives, in place and
  without a window; claiming it removes the card and confirms with a notice,
  and the page reloads by itself when an expedition comes back.
- The Guild Keeper slots are gone: group requirements scale with the players.
- Local development adds a 20-second test duration, a test player for groups
  and keeps the dev account stocked with every item.
- The Wind Rose has no daily limit and is used from the destinations step.
- The Guide Star opens a destination one level below the player's highest daily
  level, the Sky Chart one at that level; bonus destinations are badged with
  the item that opened them.

Bag and workshop
- The Watcher's bag is a grid of illustrated item cards, ordered from the
  destination items, with a short "Utiliser" button; the six missing item
  illustrations are added.
- The workshop opens in a window with illustrated commons, spare counts on the
  cards, cancel without spending anything, and shows the crafted card with its
  description and power.
- The engraving workshop picks a common first, then a tag from a chosen
  character card (in its tag colours) or from every tag, filtered by name and
  family; card lists filter by name, collection and stat.

Card sheet
- Two tabs: the card and its lore (default from the collection), and its
  improvement (default from the expeditions) with a summary of power, level,
  experience and stats.
- "Répartition des statistiques" offers Par défaut, Personnalisé and profiles,
  previews the change in the summary, and a Parchemin d'oubli resets it to
  Personnalisé so the next choice is free again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:36:01 +01:00

183 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 { bonusSlotLevel, drawExpeditionDay, ITEM_IDS } 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.");
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);
}
};