Keep destination cards unique so they can never be traded or given

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-16 22:26:52 +01:00
parent 703697f1ac
commit 994776392f
5 changed files with 75 additions and 15 deletions

View file

@ -152,6 +152,10 @@ Expéditions (migration 8, règles pures dans `services/cards/expedition-rules.j
carte de destination des Carnets qu'il n'a pas (`destinationCards.dropPct`) et, en groupe, la carte de la
destination s'il ne l'a pas (`destinationCards.groupJoinPct`). La carte d'une destination cachée est un
trophée : toujours donnée à qui y va sans l'avoir, jamais en carte de départ ni au hasard.
Une carte de destination est unique : la recevoir une seconde fois ne fait rien (`addCard`), un paquet
remplace une carte de destination déjà possédée (ou déjà tirée dans le même paquet) par une autre carte de
même rareté de sa collection, le butin d'expédition ne la tire plus, et elle ne s'échange ni ne se donne
(`DESTINATION_CARD_LOCKED`).
- `expeditions(id, mode, day, destination_id, difficulty, duration_ms, creator_id, status, setup_json,
result_json, created_at, departs_at, returns_at, completed_at)` : `mode` `solo` ou `group`,
`status` `forming`, `running`, `completed` ou `cancelled` (« revenue » se déduit de `returns_at`).

View file

@ -238,7 +238,9 @@ export class ExpeditionService {
return logbooks.length ? this.pickLogbookEdition(logbooks, random) : null;
}
const owned = new Set(playerId ? this.db.prepare("SELECT edition_id FROM collection_cards WHERE player_id = ?").all(playerId).map((row) => row.edition_id) : []);
return drawCollectionCard(this.cards.catalog, linked.id, random, { weightOf: (edition) => (owned.has(edition.id) ? 100 : settings.rewardCards.missingWeightPct) });
// Une carte de destination déjà possédée n'est jamais tirée : elle est unique.
const weightOf = (edition) => (!owned.has(edition.id) ? settings.rewardCards.missingWeightPct : this.cards.isDestinationEdition(edition.id) ? 0 : 100);
return drawCollectionCard(this.cards.catalog, linked.id, random, { weightOf });
}
// Éditions des cartes de destination illustrées ; avec `expeditionOnly`, seulement celles à trouver en expédition (collections des

View file

@ -73,15 +73,15 @@ export function drawShopPack(catalog, collectionId, random, share) {
}
// 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). Null si rien ne peut être tiré.
// `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é.
export function drawCollectionCard(catalog, collectionId, random, { weightOf = () => 1 } = {}) {
const collection = catalog.collections.find((item) => item.id === collectionId && item.active);
if (!collection?.dropWeights) return null;
const editions = collectionDrawableEditions(catalog, collectionId);
const rarityEntries = Object.entries(collection.dropWeights).filter(([rarity, weight]) => weight > 0 && editions.some((edition) => edition.rarity === rarity));
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;
const rarity = weightedChoice(rarityEntries, random);
return weightedChoice(editions.filter((edition) => edition.rarity === rarity).map((edition) => [edition.id, weightOf(edition)]), random);
return weightedChoice(ofRarity(weightedChoice(rarityEntries, random)), random);
}
// Tire les trois cartes d'un paquet. Options des paquets offerts :

View file

@ -2,7 +2,7 @@
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { normalizeReward } from "./rewards.js";
import { planRecycling, spareQuantity, validateShopSetting } from "./stardust.js";
import { FULL_ART_FORMAT, buildPublishedCatalog, createCatalogIndex, holographicFinishIds, legendaryParentEdition, MATCH_HOLO_PALETTE_ID, mythicEditionId, publicCatalog, validateRarityWeights } from "./catalog.js";
import { FULL_ART_FORMAT, buildPublishedCatalog, collectionDrawableEditions, createCatalogIndex, holographicFinishIds, legendaryParentEdition, MATCH_HOLO_PALETTE_ID, mythicEditionId, publicCatalog, validateRarityWeights } from "./catalog.js";
import { computeStreak, DAILY_REPEAT_WINDOW_DAYS, dailyDayKey, dailyZoom, drawDailyPuzzle, guessHint, isDayKey, MAX_DAILY_GUESSES, nextDailyAt, shiftDayKey } from "./daily.js";
import { calculateRecharge, pinnedRecharge, drawPack, drawShopPack, MAX_RECHARGE_INTERVAL_MS, MIN_RECHARGE_INTERVAL_MS, spendOpening } from "./game-rules.js";
import { DEFAULT_DESTINATIONS_PATH, loadExpeditionDestinations } from "./expedition-content.js";
@ -354,9 +354,34 @@ export class CardsService {
return this.db.prepare("SELECT quantity FROM collection_cards WHERE player_id = ? AND edition_id = ?").get(playerId, editionId)?.quantity ?? 0;
}
// Une carte de destination est unique : la recevoir une seconde fois ne fait rien (elle ne s'échange ni ne se donne).
// Renvoie false quand la carte n'a pas été ajoutée.
addCard(playerId, editionId) {
if (this.isDestinationEdition(editionId) && this.quantityOf(playerId, editionId)) return false;
this.db.prepare(`INSERT INTO collection_cards(player_id, edition_id, quantity, acquired_at) VALUES (?, ?, 1, ?)
ON CONFLICT(player_id, edition_id) DO UPDATE SET quantity = quantity + 1`).run(playerId, editionId, this.now());
return true;
}
isDestinationEdition(editionId) {
return this.index.cards.get(this.index.editions.get(editionId)?.cardId)?.kind === "destination";
}
// Cartes d'un paquet : une carte de destination déjà possédée, ou déjà tirée dans ce paquet, est remplacée par une autre carte de
// même rareté de sa collection (hors cartes de destination), pour ne jamais en montrer une que le joueur ne recevrait pas.
uniqueDestinationCards(playerId, editionIds) {
const seen = new Set();
return editionIds.map((editionId) => {
if (!this.isDestinationEdition(editionId)) return editionId;
if (!seen.has(editionId) && !this.quantityOf(playerId, editionId)) {
seen.add(editionId);
return editionId;
}
const edition = this.index.editions.get(editionId);
const collectionId = this.index.cards.get(edition.cardId).collectionId;
const others = collectionDrawableEditions(this.catalog, collectionId).filter((item) => item.rarity === edition.rarity && !this.isDestinationEdition(item.id));
return others.length ? others[this.random(others.length)].id : editionId;
});
}
// Retire des doublons : l'exemplaire conservé ne peut jamais partir.
@ -568,7 +593,8 @@ export class CardsService {
// Crée une ouverture en attente de révélation avec les éditions tirées ; utilisé par les paquets normaux, achetés et offerts.
// Une carte ou une édition est « nouvelle » si le joueur ne la possédait pas : une carte obtenue n'est jamais perdue.
insertOpening(playerId, collectionId, editionIds) {
insertOpening(playerId, collectionId, drawnEditionIds) {
const editionIds = this.uniqueDestinationCards(playerId, drawnEditionIds);
const openingId = randomUUID();
this.db.prepare("INSERT INTO openings(id, player_id, collection_id, status, created_at) VALUES (?, ?, ?, 'pending', ?)")
.run(openingId, playerId, collectionId, this.now());
@ -582,7 +608,7 @@ export class CardsService {
.run(openingId, position, editionId, knownCard ? 0 : 1, quantity ? 0 : 1, quantity);
this.addCard(playerId, editionId);
});
return openingId;
return { openingId, editionIds };
}
// Rejoue une requête déjà traitée (même clé d'idempotence) ou exécute `create` qui renvoie l'identifiant d'ouverture.
@ -617,8 +643,7 @@ export class CardsService {
const spent = spendOpening(this.refreshRecharge(playerId), this.now(), this.rechargeSetting);
this.db.prepare("UPDATE players SET openings_balance = ?, recharge_anchor = ? WHERE id = ?").run(spent.openingsBalance, spent.rechargeAnchor, playerId);
}
const editionIds = drawPack(this.catalog, collectionId, this.random);
const openingId = this.insertOpening(playerId, collectionId, editionIds);
const { openingId, editionIds } = this.insertOpening(playerId, collectionId, drawPack(this.catalog, collectionId, this.random));
this.audit(playerId, "pack_opened", openingId, { collectionId, cards: editionIds, ...(purchased ? { purchased: true } : {}) });
return openingId;
});
@ -669,8 +694,7 @@ export class CardsService {
this.refreshRecharge(playerId);
const paid = this.db.prepare("UPDATE players SET stardust = stardust - ? WHERE id = ? AND stardust >= ?").run(shopPackPrice, playerId, shopPackPrice);
if (!paid.changes) fail(409, "NOT_ENOUGH_STARDUST", "Pas assez de poussière d’étoiles.");
const editionIds = drawShopPack(this.catalog, collection.id, this.random, shopPackShare);
const openingId = this.insertOpening(playerId, collection.id, editionIds);
const { openingId, editionIds } = this.insertOpening(playerId, collection.id, drawShopPack(this.catalog, collection.id, this.random, shopPackShare));
this.audit(playerId, "pack_opened", openingId, { collectionId: collection.id, cards: editionIds, price: shopPackPrice });
return openingId;
});
@ -682,8 +706,7 @@ export class CardsService {
const gift = this.db.prepare("SELECT * FROM gift_packs WHERE id = ? AND player_id = ? AND opening_id IS NULL").get(giftPackId, playerId);
if (!gift) fail(404, "GIFT_PACK_NOT_FOUND", "Ce paquet offert n'est plus disponible.");
const options = JSON.parse(gift.options_json);
const editionIds = drawPack(this.catalog, gift.collection_id, this.random, { weights: options.rarityWeights, guarantee: options.guarantee, requireActive: false });
const openingId = this.insertOpening(playerId, gift.collection_id, editionIds);
const { openingId, editionIds } = this.insertOpening(playerId, gift.collection_id, drawPack(this.catalog, gift.collection_id, this.random, { weights: options.rarityWeights, guarantee: options.guarantee, requireActive: false }));
this.db.prepare("UPDATE gift_packs SET opening_id = ?, opened_at = ? WHERE id = ?").run(openingId, this.now(), gift.id);
this.audit(playerId, "gift_pack_opened", openingId, { collectionId: gift.collection_id, campaignId: gift.campaign_id, ...(gift.expedition_id ? { expeditionId: gift.expedition_id } : {}), cards: editionIds });
return openingId;
@ -909,6 +932,7 @@ export class CardsService {
this.expireTransfers();
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.");
this.requireRecipient(playerId, recipientId);
if ([editionId, requestedEditionId].some((id) => id && this.isDestinationEdition(id))) fail(409, "DESTINATION_CARD_LOCKED", "Les cartes de destination ne s’échangent pas et ne se donnent pas.");
this.requireSpare(playerId, editionId);
const now = this.now();
const insert = this.db.prepare(`INSERT INTO transfers(id, code, type, initiator_id, recipient_id, offered_edition_id, requested_edition_id, status, created_at, expires_at, completed_at)

View file

@ -210,6 +210,36 @@ test("reward cards come from the Carnets, or mostly from the destination's colle
assert.equal(draw({ rewardCollectionId: "dream-arcade", logbookCards: [] }, (max) => max - 1), "dream-arcade");
});
// Une carte de destination est unique : jamais en double, remplacée dans un paquet, jamais échangée ni donnée.
test("destination cards are unique: never twice in a collection, replaced in packs, never traded", () => {
const { service, player, database } = expeditionService({ allDestinations: false });
const other = service.upsertPlayer({ discordId: "unique-other", displayName: "Other" });
const cloud = "cosmic-cloud-heart-standard";
database.transaction(() => {
assert.equal(service.addCard(player.id, cloud), true);
assert.equal(service.addCard(player.id, cloud), false);
});
assert.equal(service.quantityOf(player.id, cloud), 1);
// Dans un paquet : déjà possédée, elle devient une autre rare de la Nébuleuse ; tirée deux fois, la seconde est remplacée.
const rarity = (editionId) => service.index.editions.get(editionId).rarity;
const collectionOf = (editionId) => service.index.cards.get(service.index.editions.get(editionId).cardId).collectionId;
const first = database.transaction(() => service.insertOpening(player.id, "primordial-nebula", [cloud, rares(service)[0], cloud]));
service.completeOpening(player.id, first.openingId);
const replaced = first.editionIds;
assert.ok(replaced.every((editionId) => !service.isDestinationEdition(editionId) || editionId !== cloud));
assert.ok(replaced.every((editionId) => rarity(editionId) === "rare" && collectionOf(editionId) === "primordial-nebula"));
const second = database.transaction(() => service.insertOpening(other.id, "primordial-nebula", [cloud, cloud, rares(service)[0]]));
service.completeOpening(other.id, second.openingId);
const fresh = second.editionIds;
assert.deepEqual(fresh.filter((editionId) => editionId === cloud), [cloud]);
assert.equal(service.quantityOf(other.id, cloud), 1);
// Ni échange ni don, même avec un ancien doublon.
database.db.prepare("UPDATE collection_cards SET quantity = 2 WHERE player_id = ? AND edition_id = ?").run(player.id, cloud);
assert.throws(() => service.createTransfer(player.id, { type: "gift", recipientId: other.id, editionId: cloud }), (error) => error.code === "DESTINATION_CARD_LOCKED");
});
const rares = (service) => editionsOf("rare").filter((editionId) => !service.isDestinationEdition(editionId));
test("unlucky rolls keep the average and never hand out a collection card", () => {
const { clock, service, player, open, rares } = expeditionService({ random: (max) => max - 1 });
open();