Let Sokko TCG players level up cards for Expeditions with Éclats or duplicates

- Each owned rare or better edition keeps a level and field experience; a level costs Éclats by current power, so every rarity reaches the same cap and a rare pays the longer road.
- A duplicate of the same edition gives a whole level; every claimed expedition grants field experience to the cards it sent.
- A one-way bridge turns stardust into Éclats at an admin-tuned rate.
- The card sheet shows level, power, stats and experience with upgrade buttons; expeditions use the upgraded power.
- Administration › Guilde tunes the cost formula, duplicate levels, field experience and the bridge rate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-15 14:52:44 +01:00
parent 6b7605d04e
commit e0ffccd1c8
22 changed files with 373 additions and 10 deletions

View file

@ -314,6 +314,15 @@ export function createCardsApiHandler({
json(res, 201, body.mode === "group" ? service.expeditions.createGroup(session.player.id, body, requestKey) : service.expeditions.startSolo(session.player.id, body, requestKey));
return true;
}
if (req.method === "POST" && url.pathname === "/api/cards/progress/upgrade") {
const body = await readBody(req);
json(res, 200, service.expeditions.upgradeCard(session.player.id, { editionId: body.editionId, method: body.method }));
return true;
}
if (req.method === "POST" && url.pathname === "/api/cards/eclats/convert") {
json(res, 200, service.expeditions.convertStardust(session.player.id, { eclats: (await readBody(req)).eclats }));
return true;
}
const expeditionGroup = routeMatch(url.pathname, /^\/api\/cards\/expeditions\/([^/]+)\/(join|leave|depart)$/);
if (req.method === "POST" && expeditionGroup) {
const [expeditionId, action] = expeditionGroup;

View file

@ -298,6 +298,18 @@ const MIGRATIONS = [
DROP TABLE gift_packs;
ALTER TABLE gift_packs_next RENAME TO gift_packs;
CREATE INDEX gift_packs_player_idx ON gift_packs(player_id, opened_at);
`,
// Améliorations des Expéditions : niveau et expérience de terrain (en % du niveau suivant) de chaque édition possédée par un joueur.
// La progression suit l'exemplaire gardé : seuls les doublons quittent une collection.
`
CREATE TABLE card_progress (
player_id TEXT NOT NULL REFERENCES players(id),
edition_id TEXT NOT NULL,
level INTEGER NOT NULL DEFAULT 0 CHECK (level >= 0),
field_xp INTEGER NOT NULL DEFAULT 0 CHECK (field_xp BETWEEN 0 AND 99),
updated_at INTEGER NOT NULL,
PRIMARY KEY (player_id, edition_id)
) STRICT;
`
];

View file

@ -0,0 +1,100 @@
// Rôle : améliorations des cartes Sokko TCG pour les Expéditions : niveaux par Éclats ou doublon, expérience de terrain, pont depuis la poussière.
// Ces méthodes s'ajoutent à ExpeditionService (Object.assign sur son prototype) et utilisent `this` comme lui.
import { editionExpeditionData, gainProgress, maxLevel, upgradeCost } from "./expedition-rules.js";
function fail(status, code, message) {
throw Object.assign(new Error(message), { status, code });
}
// 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;
export const progressMethods = {
levelsOf(playerId) {
return new Map(this.db.prepare("SELECT edition_id, level, field_xp FROM card_progress WHERE player_id = ?").all(playerId)
.map((row) => [row.edition_id, { level: row.level, fieldXp: row.field_xp }]));
},
progressOf(playerId, editionId) {
const row = this.db.prepare("SELECT level, field_xp FROM card_progress WHERE player_id = ? AND edition_id = ?").get(playerId, editionId);
return { level: row?.level ?? 0, fieldXp: row?.field_xp ?? 0 };
},
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);
return this.cards.collectionOf(playerId).map((entry) => {
const progress = levels.get(entry.editionId) || { level: 0, fieldXp: 0 };
const data = editionExpeditionData(this.cards.catalog, entry.editionId, progress.level, settings);
if (!data) return null;
return {
editionId: entry.editionId, level: progress.level, fieldXp: progress.fieldXp, power: data.power, stats: data.stats,
maxLevel: maxLevel(data.rarity, settings), nextCost: upgradeCost(data.rarity, progress.level, settings), spare: entry.spare
};
}).filter(Boolean);
},
// Monte une carte d'un niveau avec des Éclats, ou de `duplicateLevels` niveaux en consommant un doublon de la même édition.
upgradeCard(playerId, { editionId, method } = {}) {
const settings = this.settings;
if (!["eclats", "duplicate"].includes(method)) fail(400, "UPGRADE_METHOD_INVALID", "Choisissez des Éclats ou un doublon.");
this.cards.database.transaction(() => {
const owned = this.cards.collectionOf(playerId).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.");
let next;
let details;
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 (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 (!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.
gainFieldXpInTx(playerId, editionIds, settings) {
if (!settings.progression.fieldXpPct) return;
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.progression.fieldXpPct }, settings));
}
}
};

View file

@ -279,3 +279,23 @@ export function cohesionPct(playerSlots, settings) {
export function groupLootPct(players, settings) {
return settings.group.lootPct[Math.min(Math.max(players, 2), 4) - 2];
}
// Coût du niveau suivant en Éclats : il dépend de la Puissance actuelle, pas de la rareté (au moins 1). Null au plafond.
export function upgradeCost(rarity, level, settings) {
const power = cardPower(rarity, level, settings);
if (power >= settings.power.cap) return null;
return Math.max(1, settings.progression.costFactor * (power - settings.progression.costOffset));
}
// Ajoute des niveaux et de l'expérience de terrain (en % d'un niveau) sans dépasser le plafond ; au plafond, l'expérience retombe à 0.
export function gainProgress({ level, fieldXp }, rarity, { levels = 0, xpPct = 0 }, settings) {
const top = maxLevel(rarity, settings);
let nextLevel = Math.min(top, level + levels);
let nextXp = fieldXp + xpPct;
while (nextXp >= 100 && nextLevel < top) {
nextLevel += 1;
nextXp -= 100;
}
if (nextLevel >= top) nextXp = 0;
return { level: nextLevel, fieldXp: nextXp };
}

View file

@ -10,6 +10,7 @@ import {
DEFAULT_EXPEDITION_SETTINGS, diffExpeditionSettings, EXPEDITION_SETTINGS_SCHEMA, mergeExpeditionSettings, validateExpeditionSettings
} from "./expedition-settings.js";
import { groupMethods } from "./expedition-group.js";
import { progressMethods } from "./expedition-progress.js";
const HOUR_MS = 3_600_000;
@ -104,8 +105,9 @@ export class ExpeditionService {
eligibleCards(playerId, settings) {
const pending = this.db.prepare("SELECT id FROM openings WHERE player_id = ? AND status = 'pending' LIMIT 1").get(playerId);
const busy = this.busyEditions(playerId);
const levels = this.levelsOf(playerId);
return this.cards.visibleCollection(playerId, pending?.id).map((entry) => {
const data = editionExpeditionData(this.cards.catalog, entry.editionId, 0, settings);
const data = editionExpeditionData(this.cards.catalog, entry.editionId, levels.get(entry.editionId)?.level ?? 0, settings);
if (!data) return null;
const busyEntry = busy.get(entry.editionId);
return { ...data, busy: Boolean(busyEntry), busyUntil: busyEntry?.returnsAt ?? null };
@ -305,6 +307,7 @@ export class ExpeditionService {
stars: { min: settings.solo.minStars, max: settings.solo.maxStars, limit: MAX_STARS },
soloCards: settings.solo.cards,
soloLimit: settings.solo.maxConcurrent,
progression: { stardustPerEclat: settings.progression.stardustPerEclat },
group: {
stars: { min: settings.group.minStars, max: settings.group.maxStars },
slots: settings.group.slots, minPlayers: settings.group.minPlayers, limit: settings.group.maxConcurrent,
@ -338,6 +341,7 @@ export class ExpeditionService {
const waiting = this.db.prepare("SELECT COUNT(*) AS count FROM expedition_members WHERE expedition_id = ? AND claimed_at IS NULL").get(row.id).count;
if (!waiting) this.db.prepare("UPDATE expeditions SET status = 'completed', completed_at = ? WHERE id = ?").run(now, row.id);
const editionIds = this.db.prepare("SELECT edition_id FROM expedition_slots WHERE expedition_id = ? AND player_id = ? ORDER BY position").all(row.id, playerId).map((slot) => slot.edition_id);
this.gainFieldXpInTx(playerId, editionIds, this.settings);
this.cards.audit(playerId, "expedition_completed", row.id, {
destinationId: setup.destination.id, destinationName: setup.destination.name, difficulty: row.difficulty, hours: setup.hours,
mode: row.mode, players: result.players ?? 1, tier: result.tier, scorePct: result.scorePct, eclats: reward.eclats, stardust: reward.stardust, packs: reward.packs.length, editionIds
@ -426,4 +430,5 @@ export class ExpeditionService {
}
// Expéditions de groupe : tableau de la Guilde, inscription, départ, garde-fou d'inscription (expedition-group.js).
Object.assign(ExpeditionService.prototype, groupMethods);
// Améliorations : niveaux, expérience de terrain et pont depuis la poussière (expedition-progress.js).
Object.assign(ExpeditionService.prototype, groupMethods, progressMethods);

View file

@ -12,6 +12,9 @@ export const DEFAULT_EXPEDITION_SETTINGS = Object.freeze({
group: { slots: 4, minPlayers: 2, maxConcurrent: 2, minStars: 2, maxStars: 5, recruitHours: 12, lootPct: [150, 175, 200], npcStat: 8, cohesionPct: 10 },
power: { rare: 40, epic: 55, legendary: 70, mythic: 85, perLevel: 5, cap: 100 },
roles: { multiplierPct: 200 },
// Améliorations : coût d'un niveau en Éclats = costFactor × (Puissance actuelle − costOffset), niveaux donnés par un doublon,
// expérience de terrain par retour d'expédition (% d'un niveau) et taux du pont depuis la poussière (poussières pour 1 Éclat).
progression: { costFactor: 2, costOffset: 35, duplicateLevels: 1, fieldXpPct: 10, stardustPerEclat: 3 },
// Exigence d'une stat, par place, pour chaque nombre d'étoiles : stat principale, puis seconde, troisième et quatrième.
requirements: { star1: [9], star2: [11, 10], star3: [15, 14, 11], star4: [19, 18, 14], star5: [22, 21, 17, 14], conditionMissPct: 25 },
danger: { malusPct: 20, shieldMaxPct: 50, endurancePerSlot: 14 },
@ -65,6 +68,11 @@ export const EXPEDITION_SETTINGS_SCHEMA = Object.freeze([
int("power.perLevel", 0, 50),
int("power.cap", 1, 300),
int("roles.multiplierPct", 100, 400),
int("progression.costFactor", 0, 100),
int("progression.costOffset", 0, 300),
int("progression.duplicateLevels", 0, 12),
int("progression.fieldXpPct", 0, 100),
int("progression.stardustPerEclat", 1, 1000),
ints("requirements.star1", 1, 1, 1000),
ints("requirements.star2", 2, 1, 1000),
ints("requirements.star3", 3, 1, 1000),

View file

@ -37,7 +37,7 @@ const ADMIN_HISTORY_PAGE_SIZE = 50;
const PLAYER_HISTORY_EVENTS = Object.freeze([
"welcome_opening", "pack_opened", "gift_pack_opened", "cards_recycled", "opening_purchased", "campaign_claimed",
"trade_created", "trade_received", "trade_declined", "trade_joined", "trade_completed", "trade_cancelled",
"gift_created", "gift_joined", "gift_completed", "gift_cancelled", "daily_won", "expedition_completed", "expedition_cancelled_by_guild", "expedition_dissolved"
"gift_created", "gift_joined", "gift_completed", "gift_cancelled", "daily_won", "expedition_completed", "expedition_cancelled_by_guild", "expedition_dissolved", "card_upgraded", "eclats_converted"
]);
const DEV_STARDUST = 1000;
const DELETED_PLAYER_NAME = "Joueur supprimé";
@ -475,6 +475,7 @@ export class CardsService {
shop: { stardustValues: shop.stardustValues, openingPrice: shop.openingPrice, shopPackPrice: shop.shopPackPrice, shopPackShare: shop.shopPackShare, dailyReward: shop.dailyReward },
daily: this.dailySummary(playerId),
expeditions: this.expeditions.summary(playerId),
cardProgress: this.expeditions.cardProgressView(playerId),
recycling: { count: recycling.count, stardust: recycling.stardust },
pendingOpening: pending ? this.openingById(pending.id, playerId) : null,
rarestPull: this.rarestPull(playerId), stats: { openingsCount },
@ -875,7 +876,7 @@ export class CardsService {
}
this.db.prepare("UPDATE openings SET status = 'completed', completed_at = ? WHERE player_id = ? AND status = 'pending'").run(this.now(), playerId);
this.expeditions.forgetPlayer(playerId);
for (const table of ["sessions", "collection_cards", "favorites", "idempotency", "daily_attempts"]) this.db.prepare(`DELETE FROM ${table} WHERE player_id = ?`).run(playerId);
for (const table of ["sessions", "collection_cards", "favorites", "idempotency", "daily_attempts", "card_progress"]) this.db.prepare(`DELETE FROM ${table} WHERE player_id = ?`).run(playerId);
this.db.prepare("DELETE FROM gift_packs WHERE player_id = ? AND opening_id IS NULL").run(playerId);
this.db.prepare(`UPDATE players SET discord_id = ?, display_name = ?, avatar_url = '', is_admin = 0, openings_balance = 0, recharge_anchor = NULL, stardust = 0, purchased_openings = 0, eclats = 0, deleted_at = ? WHERE id = ?`)
.run(`deleted:${randomUUID()}`, DELETED_PLAYER_NAME, this.now(), playerId);