Each core file of services/cards now says where it sits, its entry points, who calls it and what to watch for: admin checks living in the service, the methods added to ExpeditionService and TeamService by Object.assign, the InTx suffix, settings defaults that do not change an existing database, and rules shared with the browser. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
145 lines
10 KiB
JavaScript
145 lines
10 KiB
JavaScript
/**
|
|
* @file Règles pures des ouvertures de paquets : recharge de la réserve dans le temps, dépense d'une ouverture,
|
|
* tirage des cartes d'un paquet de collection ou de la boutique.
|
|
*
|
|
* Utilisé par : service.js (paquets, boutique) et expedition-service.js (carte tirée en récompense).
|
|
* Attention : le hasard est passé en paramètre (`random(max)`), pour des tests reproductibles ; les taux de
|
|
* tirage viennent du catalogue publié (`dropWeights`), réglés dans l'administration.
|
|
*/
|
|
|
|
import { randomInt } from "node:crypto";
|
|
import { collectionDrawableEditions, shopPackPools } from "./catalog.js";
|
|
|
|
// Réglage de recharge unique (table recharge_settings) : un délai entre deux ouvertures et une réserve maximale.
|
|
// Un changement de délai s'applique aussi au temps déjà écoulé depuis la dernière recharge du joueur.
|
|
export const MIN_RECHARGE_INTERVAL_MS = 60_000;
|
|
export const MAX_RECHARGE_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
// Borne aussi imposée par la base (recharge_settings.max_openings) : la changer demande une migration.
|
|
export const MAX_RESERVE_OPENINGS = 50;
|
|
|
|
function checkedSetting({ intervalMs, maxOpenings }) {
|
|
if (!Number.isInteger(intervalMs) || intervalMs < 1 || !Number.isInteger(maxOpenings) || maxOpenings < 1) throw new TypeError("Recharge setting is invalid.");
|
|
return { intervalMs, maxOpenings };
|
|
}
|
|
|
|
export function calculateRecharge(player, now, setting) {
|
|
const { intervalMs, maxOpenings } = checkedSetting(setting);
|
|
const balance = Math.max(0, Number(player.openingsBalance) || 0);
|
|
// Au-dessus d'une réserve réduite depuis, le joueur garde ses ouvertures en trop : la recharge reprend une fois redescendu sous le maximum.
|
|
if (balance >= maxOpenings) return { openingsBalance: balance, rechargeAnchor: null, nextOpeningAt: null };
|
|
const anchor = player.rechargeAnchor == null ? now : Number(player.rechargeAnchor);
|
|
const earned = Math.max(0, Math.floor((now - anchor) / intervalMs));
|
|
const openingsBalance = Math.min(maxOpenings, balance + earned);
|
|
if (openingsBalance >= maxOpenings) return { openingsBalance: maxOpenings, rechargeAnchor: null, nextOpeningAt: null };
|
|
const rechargeAnchor = anchor + earned * intervalMs;
|
|
return { openingsBalance, rechargeAnchor, nextOpeningAt: rechargeAnchor + intervalMs };
|
|
}
|
|
|
|
// Réserve figée juste sous le maximum, pour le compte de développement : le minuteur continue de tourner et repart à chaque échéance.
|
|
export function pinnedRecharge(player, now, setting) {
|
|
const { intervalMs, maxOpenings } = checkedSetting(setting);
|
|
const anchor = player.rechargeAnchor == null ? now : Number(player.rechargeAnchor);
|
|
const rechargeAnchor = anchor + Math.max(0, Math.floor((now - anchor) / intervalMs)) * intervalMs;
|
|
return { openingsBalance: Math.max(1, maxOpenings - 1), rechargeAnchor, nextOpeningAt: rechargeAnchor + intervalMs };
|
|
}
|
|
|
|
export function spendOpening(recharge, now, setting) {
|
|
const { intervalMs, maxOpenings } = checkedSetting(setting);
|
|
if (recharge.openingsBalance < 1) throw Object.assign(new Error("Aucune ouverture disponible."), { status: 409, code: "NO_OPENING" });
|
|
const wasFull = recharge.openingsBalance >= maxOpenings || recharge.rechargeAnchor == null;
|
|
const rechargeAnchor = wasFull ? now : recharge.rechargeAnchor;
|
|
return { openingsBalance: recharge.openingsBalance - 1, rechargeAnchor, nextOpeningAt: rechargeAnchor + intervalMs };
|
|
}
|
|
|
|
function weightedChoice(entries, random = (max) => randomInt(max)) {
|
|
const total = entries.reduce((sum, [, weight]) => sum + weight, 0);
|
|
if (total <= 0) throw new TypeError("A weighted choice needs a positive total.");
|
|
let cursor = random(total);
|
|
for (const [value, weight] of entries) {
|
|
cursor -= weight;
|
|
if (cursor < 0) return value;
|
|
}
|
|
return entries.at(-1)[0];
|
|
}
|
|
|
|
const pick = (random, max) => (random || ((limit) => randomInt(limit)))(max);
|
|
|
|
// Quand une légendaire ou une mythique sort du paquet de la Boutique, `share` % des tirages reviennent aux cartes de sa collection, quel que soit leur nombre.
|
|
export function drawShopPack(catalog, collectionId, random, share) {
|
|
const collection = catalog.collections.find((item) => item.id === collectionId && item.active);
|
|
if (!collection) throw Object.assign(new Error("Ce paquet n'est pas disponible."), { status: 404, code: "COLLECTION_UNAVAILABLE" });
|
|
if (!collection.dropWeights) throw new TypeError(`No drop rates for ${collectionId}.`);
|
|
const { others, featured } = shopPackPools(catalog, collectionId);
|
|
const ofRarity = (editions, rarity) => editions.filter((edition) => edition.rarity === rarity);
|
|
const rarityEntries = Object.entries(collection.dropWeights).filter(([rarity, weight]) => weight > 0 && (ofRarity(others, rarity).length || ofRarity(featured, rarity).length));
|
|
if (!rarityEntries.length) throw Object.assign(new Error("Aucune carte ne peut être tirée avec ces taux."), { status: 409, code: "NOTHING_DRAWABLE" });
|
|
return Array.from({ length: 3 }, () => {
|
|
const rarity = weightedChoice(rarityEntries, random);
|
|
const featuredCandidates = ofRarity(featured, rarity);
|
|
const otherCandidates = ofRarity(others, rarity);
|
|
const useFeatured = featuredCandidates.length > 0 && (!otherCandidates.length || pick(random, 100) < share);
|
|
const candidates = useFeatured ? featuredCandidates : otherCandidates;
|
|
return candidates[pick(random, candidates.length)].id;
|
|
});
|
|
}
|
|
|
|
// Tire une seule carte d'une collection ouverte, avec ses taux de tirage (une légendaire peut sortir en variation mythique).
|
|
// `weightOf(edition)` pondère les éditions dans la rareté tirée (par défaut, toutes à 1 ; 0 l'exclut). Null si rien ne peut être tiré.
|
|
// `requireActive: false` : la collection peut être fermée (butin des Expéditions, qui en rattrape les cartes).
|
|
export function drawCollectionCard(catalog, collectionId, random, { weightOf = () => 1, requireActive = true } = {}) {
|
|
const collection = catalog.collections.find((item) => item.id === collectionId && (item.active || !requireActive));
|
|
if (!collection?.dropWeights) return null;
|
|
const weighted = collectionDrawableEditions(catalog, collectionId).map((edition) => [edition, weightOf(edition)]).filter(([, weight]) => weight > 0);
|
|
const ofRarity = (rarity) => weighted.filter(([edition]) => edition.rarity === rarity).map(([edition, weight]) => [edition.id, weight]);
|
|
const rarityEntries = Object.entries(collection.dropWeights).filter(([rarity, weight]) => weight > 0 && ofRarity(rarity).length);
|
|
if (!rarityEntries.length) return null;
|
|
return weightedChoice(ofRarity(weightedChoice(rarityEntries, random)), random);
|
|
}
|
|
|
|
// Tire les trois cartes d'un paquet. Options des paquets offerts :
|
|
// - `weights` : poids personnalisés (sinon, ou s'ils ne permettent plus rien de tirer, ceux de la collection) ;
|
|
// - `guarantee` : { type: "rarity", rarity, count } (au moins `count` cartes de cette rareté ou mieux)
|
|
// ou { type: "edition", editionId } (cette variation figure dans le paquet) ;
|
|
// - `requireActive` : un paquet offert s'ouvre même si la collection est fermée.
|
|
export function drawPack(catalog, collectionId, random, { weights = null, guarantee = null, requireActive = true } = {}) {
|
|
const collection = catalog.collections.find((item) => item.id === collectionId && (item.active || !requireActive));
|
|
if (!collection) throw Object.assign(new Error("Cette collection n'est pas disponible."), { status: 404, code: "COLLECTION_UNAVAILABLE" });
|
|
const cardIds = new Set(catalog.cards.filter((card) => card.collectionId === collectionId).map((card) => card.id));
|
|
const editions = collectionDrawableEditions(catalog, collectionId);
|
|
const drawable = (rarity) => editions.some((edition) => edition.rarity === rarity);
|
|
const entriesOf = (candidate) => Object.entries(candidate || {}).filter(([rarity, weight]) => weight > 0 && drawable(rarity));
|
|
// Des poids personnalisés devenus intirables (cartes retirées depuis) se replient sur les taux du paquet au lieu de bloquer l'ouverture.
|
|
const rarityWeights = weights && (entriesOf(weights).length || !collection.dropWeights) ? weights : collection.dropWeights;
|
|
if (!rarityWeights) throw new TypeError(`No drop rates for ${collectionId}.`);
|
|
const rarityEntries = entriesOf(rarityWeights);
|
|
if (!rarityEntries.length) throw Object.assign(new Error("Aucune carte ne peut être tirée avec ces taux."), { status: 409, code: "NOTHING_DRAWABLE" });
|
|
const rank = new Map(catalog.rarities.map((rarity, index) => [rarity.id, index]));
|
|
const slots = Array.from({ length: 3 }, () => weightedChoice(rarityEntries, random));
|
|
|
|
if (guarantee?.type === "rarity") {
|
|
const eligible = catalog.rarities.filter((rarity) => rank.get(rarity.id) >= rank.get(guarantee.rarity) && drawable(rarity.id)).map((rarity) => rarity.id);
|
|
if (!eligible.length) throw Object.assign(new Error("Aucune carte de cette rareté ou mieux ne peut être tirée."), { status: 409, code: "GUARANTEE_UNAVAILABLE" });
|
|
const weighted = eligible.map((rarity) => [rarity, rarityWeights[rarity] || 0]).filter(([, weight]) => weight > 0);
|
|
let missing = guarantee.count - slots.filter((rarity) => rank.get(rarity) >= rank.get(guarantee.rarity)).length;
|
|
// On améliore d'abord les cartes les plus communes.
|
|
const order = slots.map((rarity, index) => index).sort((left, right) => rank.get(slots[left]) - rank.get(slots[right]));
|
|
for (const index of order) {
|
|
if (missing <= 0) break;
|
|
if (rank.get(slots[index]) >= rank.get(guarantee.rarity)) continue;
|
|
slots[index] = weighted.length ? weightedChoice(weighted, random) : eligible[0];
|
|
missing -= 1;
|
|
}
|
|
}
|
|
|
|
const picked = slots.map((rarity) => {
|
|
const candidates = editions.filter((edition) => edition.rarity === rarity);
|
|
return candidates[pick(random, candidates.length)];
|
|
});
|
|
if (guarantee?.type === "edition" && !picked.some((edition) => edition.id === guarantee.editionId)) {
|
|
const guaranteed = catalog.editions.find((edition) => edition.id === guarantee.editionId && cardIds.has(edition.cardId));
|
|
if (!guaranteed) throw Object.assign(new Error("La carte garantie n'appartient pas à cette collection."), { status: 409, code: "GUARANTEE_UNAVAILABLE" });
|
|
const lowest = picked.reduce((best, edition, index) => (rank.get(edition.rarity) < rank.get(picked[best].rarity) ? index : best), 0);
|
|
picked[lowest] = guaranteed;
|
|
}
|
|
return picked.map((edition) => edition.id);
|
|
}
|