sokko-g/services/cards/expedition-progress.js
Shinuwa 0ecb2cdbc5 Make duplicates awaken cards at Power 70, 85 and 100
Opening packs stays useful once a collection is complete: the level that reaches an awakening tier can no longer be bought with Éclats, a duplicate or field experience. The card awakens without Éclats, with one of its own duplicates (a mythic also takes its legendary version) or with duplicates of its collection and rarity: 6 rares, 2 epics or 1 legendary, numbers that follow the 24/8/3 drop rates so a tier costs about the same packs at every rarity. Tiers and counts are admin settings, and the balance guide records the simulations and the options set aside.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 09:40:41 +01:00

228 lines
17 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 : améliorations des cartes Sokko TCG pour les Expéditions : niveaux par Éclats ou doublon, Éveil aux paliers, expérience de terrain, plans de progression
// (vocation ou points libres, changés avec un Parchemin d'oubli), pont depuis la poussière et achat des objets de la boutique.
// Ces méthodes s'ajoutent à ExpeditionService (Object.assign sur son prototype) et utilisent `this` comme lui.
import { allocationError, awakeningPower, awakeningsAhead, cardExpeditionData, clampAllocation, editionExpeditionData, gainProgress, levelPoints, maxLevel, maxStatPoints, PLAN_IDS, planStats, SHOP_ITEM_PRICES, splitPower, STAT_IDS, upgradeCost, VOCATION_IDS } from "./expedition-rules.js";
function fail(status, code, message) {
throw Object.assign(new Error(message), { status, code });
}
// Plan encore ouvert : la carte suit sa collection, ou elle est en libre sans aucun point placé ; choisir y est gratuit.
const openPlan = (plan, allocation) => plan === "collection" || (plan === "free" && STAT_IDS.every((stat) => !(allocation?.[stat] > 0)));
// Au plus ce nombre d'Éclats par conversion, pour qu'une faute de frappe ne vide pas un solde de poussière.
export const MAX_CONVERT_ECLATS = 10_000;
// Au plus ce nombre d'objets par achat en boutique.
export const MAX_ITEMS_PER_PURCHASE = 100;
const readAllocation = (json) => (json ? JSON.parse(json) : null);
export const progressMethods = {
levelsOf(playerId) {
return new Map(this.db.prepare("SELECT edition_id, level, field_xp, plan, allocation_json FROM card_progress WHERE player_id = ?").all(playerId)
.map((row) => [row.edition_id, { level: row.level, fieldXp: row.field_xp, plan: row.plan, allocation: readAllocation(row.allocation_json) }]));
},
progressOf(playerId, editionId) {
const row = this.db.prepare("SELECT level, field_xp, plan, allocation_json FROM card_progress WHERE player_id = ? AND edition_id = ?").get(playerId, editionId);
return { level: row?.level ?? 0, fieldXp: row?.field_xp ?? 0, plan: row?.plan ?? null, allocation: readAllocation(row?.allocation_json) };
},
writeProgress(playerId, editionId, { level, fieldXp }) {
this.db.prepare(`INSERT INTO card_progress(player_id, edition_id, level, field_xp, updated_at) VALUES (?, ?, ?, ?, ?)
ON CONFLICT(player_id, edition_id) DO UPDATE SET level = excluded.level, field_xp = excluded.field_xp, updated_at = excluded.updated_at`)
.run(playerId, editionId, level, fieldXp, this.now());
},
// Progression de chaque carte jouable du joueur : niveau, expérience, Puissance, stats, niveau maximal et coût du suivant.
cardProgressView(playerId, settings = this.settings) {
const levels = this.levelsOf(playerId);
const equipment = this.equipmentOf(playerId);
const engravings = this.engravingsOf(playerId);
const collection = this.cards.collectionOf(playerId);
return collection.map((entry) => {
const progress = levels.get(entry.editionId) || { level: 0, fieldXp: 0, plan: null, allocation: null };
const data = this.loadout(entry.editionId, progress, equipment.get(entry.editionId), settings, engravings);
if (!data) return null;
return {
editionId: entry.editionId, level: progress.level, fieldXp: progress.fieldXp, power: data.power, baseStats: data.baseStats, stats: data.stats,
plan: this.planView(data, progress, settings),
maxLevel: maxLevel(data.rarity, settings), nextCost: upgradeCost(data.rarity, progress.level, settings), spare: entry.spare,
awakening: this.awakeningOf(entry.editionId, data.rarity, progress.level, collection, settings),
awakeningsAhead: awakeningsAhead(data.rarity, progress.level, settings),
slots: data.slots, maxSlots: settings.equipment.maxPerCard, tags: data.tags, equipment: data.equipment,
slotPowers: [0, settings.equipment.secondSlotPower, settings.equipment.thirdSlotPower].slice(0, settings.equipment.maxPerCard)
};
}).filter(Boolean);
},
// Plan de progression d'une carte : plan choisi, points de niveau (placés en libre), plafond par stat, et les stats que donnerait
// chaque vocation (sans équipement) pour l'aperçu. `paid` : changer de plan coûterait un Parchemin d'oubli ; le choix reste
// gratuit tant que la carte suit sa collection, ou en libre sans aucun point placé (après une réinitialisation).
planView(data, progress, settings) {
const profile = cardExpeditionData(this.cards.catalog, data.cardId).profile;
const points = levelPoints(data.rarity, data.level, settings);
const plan = progress.plan ?? "collection";
const preview = (id) => planStats(data.rarity, data.level, profile, { plan: id }, settings);
const allocation = plan === "free" ? clampAllocation(progress.allocation, points, settings) : null;
return {
id: plan, points, maxStatPoints: maxStatPoints(points, settings), paid: !openPlan(plan, allocation),
allocation,
levelBase: splitPower(data.power - points, profile),
previews: Object.fromEntries(["collection", ...VOCATION_IDS].map((id) => [id, preview(id)]))
};
},
// Change le plan de progression d'une carte. Tant qu'elle suit sa collection, ou en libre sans point placé, choisir est gratuit ;
// sinon, changer de plan ou retirer des points placés en libre consomme un Parchemin d'oubli (ajouter des points en libre reste
// gratuit). Réinitialiser, c'est passer en libre sans aucun point : un Parchemin, puis un nouveau choix gratuit.
setCardPlan(playerId, { editionId, plan, allocation = null } = {}) {
const settings = this.settings;
if (!PLAN_IDS.includes(plan)) fail(400, "PLAN_INVALID", "Plan de progression inconnu.");
this.cards.database.transaction(() => {
if (!this.cards.collectionOf(playerId).some((entry) => entry.editionId === editionId)) fail(404, "CARD_NOT_OWNED", "Vous ne possédez pas cette carte.");
const data = editionExpeditionData(this.cards.catalog, editionId, 0, settings);
if (!data) fail(400, "EXPEDITION_CARD_INVALID", "Seules les cartes rares, épiques, légendaires et mythiques ont un plan de progression.");
if (this.busyEditions(playerId).has(editionId)) fail(409, "EXPEDITION_CARD_BUSY", "Cette carte est en expédition : son plan ne change pas avant son retour.");
const progress = this.progressOf(playerId, editionId);
const points = levelPoints(data.rarity, progress.level, settings);
const current = progress.plan ?? "collection";
let next = null;
if (plan === "free") {
const error = allocationError(allocation, points, settings);
if (error) fail(400, "ALLOCATION_INVALID", error);
next = Object.fromEntries(STAT_IDS.map((stat) => [stat, allocation[stat] ?? 0]));
}
const placed = current === "free" ? clampAllocation(progress.allocation, points, settings) : null;
if (plan === current && (plan !== "free" || STAT_IDS.every((stat) => next[stat] === placed[stat]))) return;
const onlyAdds = plan === "free" && current === "free" && STAT_IDS.every((stat) => next[stat] >= placed[stat]);
const paid = !openPlan(current, placed) && !onlyAdds;
if (paid) this.consumeItemInTx(playerId, "oblivion");
this.db.prepare(`INSERT INTO card_progress(player_id, edition_id, level, field_xp, plan, allocation_json, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(player_id, edition_id) DO UPDATE SET plan = excluded.plan, allocation_json = excluded.allocation_json, updated_at = excluded.updated_at`)
.run(playerId, editionId, progress.level, progress.fieldXp, plan === "collection" ? null : plan, next ? JSON.stringify(next) : null, this.now());
this.cards.audit(playerId, "card_plan_changed", editionId, { plan, ...(next ? { allocation: next } : {}), oblivion: paid });
});
return { progress: this.cardProgressView(playerId, settings).find((item) => item.editionId === editionId), state: this.cards.getState(playerId) };
},
// Achète des objets de la boutique (Parchemin d'oubli, Rose des vents) avec de la poussière d'étoiles, au prix réglé dans la boutique.
buyShopItem(playerId, { item, count = 1 } = {}) {
const settings = this.settings;
if (!Object.hasOwn(SHOP_ITEM_PRICES, item)) fail(400, "ITEM_INVALID", "Cet objet ne se vend pas en boutique.");
if (!Number.isInteger(count) || count < 1 || count > MAX_ITEMS_PER_PURCHASE) fail(400, "PURCHASE_INVALID", `Quantité invalide : un entier entre 1 et ${MAX_ITEMS_PER_PURCHASE}.`);
if (!settings.enabled) fail(409, "EXPEDITIONS_CLOSED", "Les Expéditions sont fermées pour le moment.");
const cost = count * settings.progression[SHOP_ITEM_PRICES[item]];
this.cards.database.transaction(() => {
this.cards.refreshRecharge(playerId);
const paid = this.db.prepare("UPDATE players SET stardust = stardust - ? WHERE id = ? AND stardust >= ?").run(cost, playerId, cost);
if (!paid.changes) fail(409, "NOT_ENOUGH_STARDUST", "Pas assez de poussière d’étoiles.");
this.addItemsInTx(playerId, Array.from({ length: count }, () => item));
this.cards.audit(playerId, "item_bought", "shop", { item, count, stardust: cost });
});
return this.cards.getState(playerId);
},
// Éveil d'une carte arrêtée devant un palier, ou null : la Puissance du palier, le doublon de la même carte qui l'éveille
// (`exact`, pour une mythique sa version légendaire aussi) et les doublons de sa collection et de sa rareté qui le remplacent
// (`needed` au plus, choisis dans `picks` : les plus nombreux d'abord, une mythique en dernier ; vide s'il en manque).
awakeningOf(editionId, rarity, level, collection, settings) {
const power = awakeningPower(rarity, level, settings);
if (power == null) return null;
const { editions, cards } = this.cards.index;
const edition = editions.get(editionId);
const collectionId = cards.get(edition.cardId)?.collectionId;
const rarityOf = (entry) => editions.get(entry.editionId)?.rarity;
const sameCard = (entry) => editions.get(entry.editionId)?.cardId === edition.cardId;
const spares = collection.filter((entry) => entry.spare > 0);
const exact = spares.find((entry) => entry.editionId === editionId)
?? (rarity === "mythic" ? spares.find((entry) => sameCard(entry) && rarityOf(entry) === "legendary") : null);
const accepted = rarity === "mythic" ? ["legendary", "mythic"] : [rarity];
const pool = spares
.filter((entry) => !sameCard(entry) && accepted.includes(rarityOf(entry)) && cards.get(editions.get(entry.editionId)?.cardId)?.collectionId === collectionId)
.sort((left, right) => (rarityOf(left) === "mythic") - (rarityOf(right) === "mythic") || right.spare - left.spare || left.editionId.localeCompare(right.editionId));
const needed = settings.awakening[rarity];
const picks = [];
let missing = needed;
for (const entry of pool) {
if (missing <= 0) break;
const count = Math.min(entry.spare, missing);
picks.push({ editionId: entry.editionId, count });
missing -= count;
}
return { power, exact: exact?.editionId ?? null, needed, available: pool.reduce((total, entry) => total + entry.spare, 0), picks: missing > 0 ? [] : picks };
},
// Monte une carte d'un niveau avec des Éclats, ou de `duplicateLevels` niveaux en consommant un doublon de la même édition.
// Devant un palier, seul l'Éveil la fait monter, sans Éclats : un doublon de la même carte (`duplicate`) ou des doublons de sa
// collection et de sa rareté (`awaken`).
upgradeCard(playerId, { editionId, method } = {}) {
const settings = this.settings;
if (!["eclats", "duplicate", "awaken"].includes(method)) fail(400, "UPGRADE_METHOD_INVALID", "Choisissez des Éclats, un doublon ou un Éveil.");
this.cards.database.transaction(() => {
const collection = this.cards.collectionOf(playerId);
const owned = collection.find((entry) => entry.editionId === editionId);
if (!owned) fail(404, "CARD_NOT_OWNED", "Vous ne possédez pas cette carte.");
const data = editionExpeditionData(this.cards.catalog, editionId, 0, settings);
if (!data) fail(400, "EXPEDITION_CARD_INVALID", "Seules les cartes rares, épiques, légendaires et mythiques s’améliorent.");
const progress = this.progressOf(playerId, editionId);
const cost = upgradeCost(data.rarity, progress.level, settings);
if (cost == null) fail(409, "CARD_MAX_LEVEL", "Cette carte a atteint la Puissance maximale.");
const awakening = this.awakeningOf(editionId, data.rarity, progress.level, collection, settings);
let next;
let details;
if (method !== "eclats" && 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.");
if (awakening) {
if (method === "eclats") fail(409, "AWAKENING_REQUIRED", `Cette carte atteint un palier d’Éveil (Puissance ${awakening.power}) : éveillez-la avec des doublons.`);
const used = method === "duplicate" ? (awakening.exact ? [{ editionId: awakening.exact, count: 1 }] : []) : awakening.picks;
if (!used.length) fail(409, "NOT_ENOUGH_DUPLICATES", method === "duplicate" ? "Il faut un doublon libre de cette carte." : `Il faut ${awakening.needed} doublons libres de cette rareté et de cette collection.`);
for (const item of used) this.cards.removeDuplicates(playerId, item.editionId, item.count);
next = { level: progress.level + 1, fieldXp: 0 };
details = { method, awakened: awakening.power, used };
} else if (method === "awaken") {
fail(409, "NOT_AT_AWAKENING", "Cette carte n’est pas devant un palier d’Éveil.");
} else if (method === "eclats") {
const paid = this.db.prepare("UPDATE players SET eclats = eclats - ? WHERE id = ? AND eclats >= ?").run(cost, playerId, cost);
if (!paid.changes) fail(409, "NOT_ENOUGH_ECLATS", "Pas assez d’Éclats d’étoile.");
next = gainProgress(progress, data.rarity, { levels: 1 }, settings);
details = { method, eclats: cost };
} else {
if (settings.progression.duplicateLevels < 1) fail(409, "UPGRADE_METHOD_INVALID", "Les doublons ne donnent pas de niveau pour le moment.");
if (!owned.spare) fail(409, "NOT_A_DUPLICATE", "Il faut un doublon libre de cette carte.");
this.cards.removeDuplicates(playerId, editionId, 1);
next = gainProgress(progress, data.rarity, { levels: settings.progression.duplicateLevels }, settings);
details = { method };
}
this.writeProgress(playerId, editionId, next);
this.cards.audit(playerId, "card_upgraded", editionId, { ...details, level: next.level, power: editionExpeditionData(this.cards.catalog, editionId, next.level, settings).power });
});
return { progress: this.cardProgressView(playerId, settings).find((item) => item.editionId === editionId), state: this.cards.getState(playerId) };
},
// Pont à sens unique : de la poussière vers les Éclats, au taux réglé. La conversion inverse n'existe pas.
convertStardust(playerId, { eclats } = {}) {
const settings = this.settings;
if (!Number.isInteger(eclats) || eclats < 1 || eclats > MAX_CONVERT_ECLATS) fail(400, "CONVERT_INVALID", `Nombre d’Éclats invalide : un entier entre 1 et ${MAX_CONVERT_ECLATS.toLocaleString("fr-FR")}.`);
const cost = eclats * settings.progression.stardustPerEclat;
this.cards.database.transaction(() => {
// Compte de développement : son solde figé doit être appliqué avant de vérifier le prix.
this.cards.refreshRecharge(playerId);
const paid = this.db.prepare("UPDATE players SET stardust = stardust - ?, eclats = eclats + ? WHERE id = ? AND stardust >= ?").run(cost, eclats, playerId, cost);
if (!paid.changes) fail(409, "NOT_ENOUGH_STARDUST", "Pas assez de poussière d’étoiles.");
this.cards.audit(playerId, "eclats_converted", "bridge", { eclats, stardust: cost });
});
return this.cards.getState(playerId);
},
// Expérience de terrain : chaque carte du joueur revenue d'expédition gagne une part de niveau, proportionnelle à la durée choisie
// (`fieldXpPct` par tranche de `fieldXpHours` heures ; une expédition sans durée connue compte une tranche).
gainFieldXpInTx(playerId, editionIds, settings, hours = null) {
if (!settings.progression.fieldXpPct) return;
const xpPct = Math.round(settings.progression.fieldXpPct * (Number(hours) > 0 ? hours / settings.progression.fieldXpHours : 1));
for (const editionId of editionIds) {
const data = editionExpeditionData(this.cards.catalog, editionId, 0, settings);
if (!data || !this.cards.quantityOf(playerId, editionId)) continue;
this.writeProgress(playerId, editionId, gainProgress(this.progressOf(playerId, editionId), data.rarity, { xpPct }, settings));
}
}
};