sokko-g/services/cards/daily.js
Shinuwa fc43444995
Some checks failed
Validate and deploy Sokko G / validate (push) Successful in 22m10s
Validate and deploy Sokko G / deploy (push) Failing after 25s
Give each player their own daily card and send only the visible crop of its illustration
- Each player draws their own daily card and zoom point on their first visit, so a shared answer no longer helps; the migration keeps past games with their day's shared card.
- The server crops the illustration with sharp to the part visible at the current zoom; the full image only arrives once the game is over.
- The admin overview shows the day's winners and players instead of a single card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 16:47:52 +01:00

108 lines
5.4 KiB
JavaScript

// Rôle : règles pures de la Carte du jour (jour de Paris, tirage de la carte, indices, zoom et série de victoires).
// Le service les applique avec la base ; aucune fonction ici ne lit la base ni l'horloge.
import { randomInt } from "node:crypto";
export const MAX_DAILY_GUESSES = 6;
// Une carte tirée ne revient pas avant ce nombre de jours, tant qu'il reste d'autres cartes.
export const DAILY_REPEAT_WINDOW_DAYS = 60;
// Échelle de l'image selon le nombre d'essais ratés ; la partie finie montre l'image entière (échelle 1).
export const DAILY_ZOOM_STEPS = Object.freeze([6, 4.2, 3, 2.2, 1.5, 1.15]);
// Le point zoomé évite seulement les bords de l'illustration, souvent vides : il peut tomber loin du sujet.
const FOCUS_MIN = 20;
const FOCUS_MAX = 80;
const DAY_KEY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
const DAY_MS = 24 * 60 * 60 * 1000;
// Le jour change à minuit, heure de Paris : en-CA formate la date en AAAA-MM-JJ.
const parisDate = new Intl.DateTimeFormat("en-CA", { timeZone: "Europe/Paris", year: "numeric", month: "2-digit", day: "2-digit" });
export function dailyDayKey(now) {
return parisDate.format(new Date(now));
}
export function isDayKey(value) {
return typeof value === "string" && DAY_KEY_PATTERN.test(value);
}
// Calendrier pur : décale une clé de jour de `days` jours, sans fuseau horaire.
export function shiftDayKey(dayKey, days) {
const [, year, month, day] = dayKey.match(DAY_KEY_PATTERN);
return new Date(Date.UTC(Number(year), Number(month) - 1, Number(day)) + days * DAY_MS).toISOString().slice(0, 10);
}
// Instant du prochain minuit à Paris (UTC+1 en hiver, UTC+2 en été).
export function nextDailyAt(now) {
const next = shiftDayKey(dailyDayKey(now), 1);
const midnightUtc = Date.parse(`${next}T00:00:00Z`);
for (const offsetHours of [1, 2]) {
const candidate = midnightUtc - offsetHours * 3_600_000;
if (dailyDayKey(candidate) === next && dailyDayKey(candidate - 1) !== next) return candidate;
}
return midnightUtc;
}
// Rareté de référence d'une carte : celle de son édition standard. Les mythiques sont des variations d'une légendaire.
export function cardRarity(catalog, cardId) {
const editions = catalog.editions.filter((edition) => edition.cardId === cardId && edition.rarity !== "mythic");
return (editions.find((edition) => !edition.promotional) || editions[0])?.rarity ?? null;
}
// Cartes que la Carte du jour peut tirer : celles des collections ouvertes, pour ne jamais dévoiler une collection fermée,
// et illustrées, puisque le jeu se joue sur l'illustration (le catalogue admet une carte encore sans image).
export function dailyCandidates(catalog) {
const active = new Set(catalog.collections.filter((collection) => collection.active).map((collection) => collection.id));
return catalog.cards.filter((card) => card.image && active.has(card.collectionId) && cardRarity(catalog, card.id));
}
// `random(max)` renvoie un entier dans [0, max), comme pour les paquets.
export function drawDailyPuzzle(catalog, recentCardIds = [], random = (max) => randomInt(max)) {
const candidates = dailyCandidates(catalog);
if (!candidates.length) return null;
const recent = new Set(recentCardIds);
const fresh = candidates.filter((card) => !recent.has(card.id));
const pool = fresh.length ? fresh : candidates;
const card = pool[random(pool.length)];
const span = FOCUS_MAX - FOCUS_MIN + 1;
return { cardId: card.id, focusX: FOCUS_MIN + random(span), focusY: FOCUS_MIN + random(span) };
}
// Zone de l'illustration visible au zoom `zoom` autour du point `focus` (en %), comme un agrandissement CSS de même origine :
// le serveur n'envoie que ce morceau. Un zoom de 1 ou moins rend l'illustration entière.
export function dailyCrop(width, height, focus, zoom) {
if (!(zoom > 1)) return { left: 0, top: 0, width, height };
const cropWidth = Math.max(1, Math.round(width / zoom));
const cropHeight = Math.max(1, Math.round(height / zoom));
const offset = (size, crop, percent) => Math.min(size - crop, Math.max(0, Math.round((size - crop) * percent / 100)));
return { left: offset(width, cropWidth, focus.x), top: offset(height, cropHeight, focus.y), width: cropWidth, height: cropHeight };
}
// Indice d'un essai : bonne collection ou non, et rareté de la réponse par rapport à celle de l'essai.
export function guessHint(catalog, answerId, guessId) {
const cards = new Map(catalog.cards.map((card) => [card.id, card]));
const rank = new Map(catalog.rarities.map((rarity, index) => [rarity.id, index]));
const answerRank = rank.get(cardRarity(catalog, answerId));
const guessRank = rank.get(cardRarity(catalog, guessId));
return {
cardId: guessId,
correct: guessId === answerId,
sameCollection: cards.get(guessId)?.collectionId === cards.get(answerId)?.collectionId,
rarity: answerRank === guessRank ? "equal" : answerRank > guessRank ? "higher" : "lower"
};
}
export function dailyZoom(wrongCount, finished) {
if (finished) return 1;
return DAILY_ZOOM_STEPS[Math.min(Math.max(0, wrongCount), DAILY_ZOOM_STEPS.length - 1)];
}
// Jours consécutifs gagnés, jusqu'à aujourd'hui ou, si la partie du jour n'est pas encore gagnée, jusqu'à hier.
export function computeStreak(wonDayKeys, todayKey) {
const won = new Set(wonDayKeys);
let day = won.has(todayKey) ? todayKey : shiftDayKey(todayKey, -1);
let streak = 0;
while (won.has(day)) {
streak += 1;
day = shiftDayKey(day, -1);
}
return streak;
}