Add the server-backed card game: Discord login, recharging pack openings, album, trades, gifts, stardust shop, campaign codes and its administration, stored in SQLite and disabled in production until configured. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
125 lines
8.6 KiB
JavaScript
125 lines
8.6 KiB
JavaScript
// Rôle : calcule la recharge des ouvertures et sélectionne les éditions d'un paquet.
|
|
import { randomInt } from "node:crypto";
|
|
import { isDrawableEdition } 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;
|
|
|
|
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);
|
|
if (balance >= maxOpenings) return { openingsBalance: maxOpenings, 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);
|
|
|
|
// Paquet de la Boutique : les cartes de toutes les autres collections actives, plus les légendaires et mythiques de sa propre collection.
|
|
// Quand une de ces deux raretés sort, `share` % des tirages reviennent aux cartes de sa collection, quel que soit leur nombre.
|
|
const FEATURED_RARITIES = new Set(["legendary", "mythic"]);
|
|
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 sourceOf = new Map(catalog.cards.map((card) => [card.id, card.collectionId]));
|
|
const activeIds = new Set(catalog.collections.filter((item) => item.active && item.packCategory !== "shop").map((item) => item.id));
|
|
const drawableEditions = catalog.editions.filter(isDrawableEdition);
|
|
const others = drawableEditions.filter((edition) => activeIds.has(sourceOf.get(edition.cardId)));
|
|
const featured = drawableEditions.filter((edition) => sourceOf.get(edition.cardId) === collectionId && FEATURED_RARITIES.has(edition.rarity));
|
|
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 les trois cartes d'un paquet. Options des paquets offerts :
|
|
// - `weights` : poids personnalisés (sinon 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 rarityWeights = weights || collection.dropWeights;
|
|
if (!rarityWeights) throw new TypeError(`No drop rates for ${collectionId}.`);
|
|
const cardIds = new Set(catalog.cards.filter((card) => card.collectionId === collectionId).map((card) => card.id));
|
|
const editions = catalog.editions.filter((edition) => cardIds.has(edition.cardId) && isDrawableEdition(edition));
|
|
const drawable = (rarity) => editions.some((edition) => edition.rarity === rarity);
|
|
const rarityEntries = Object.entries(rarityWeights).filter(([rarity, weight]) => weight > 0 && drawable(rarity));
|
|
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);
|
|
}
|