Each core file of services/cards now says where it sits, its entry points, who calls it and what to watch for: admin checks living in the service, the methods added to ExpeditionService and TeamService by Object.assign, the InTx suffix, settings defaults that do not change an existing database, and rules shared with the browser. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
205 lines
10 KiB
JavaScript
205 lines
10 KiB
JavaScript
/**
|
|
* @file Indices de la Carte du jour : sujet (arbre) et thème du nom de chaque carte, comparaison d'un essai,
|
|
* description partielle et nom à trous.
|
|
*
|
|
* Utilisé par : service.js.
|
|
* Dépend de : content/daily-clues.json (sujet et mots de recherche de chaque carte).
|
|
* Attention : règles pures. Une nouvelle carte doit recevoir ses indices dans content/daily-clues.json.
|
|
* @see docs/carte-du-jour.md
|
|
*/
|
|
|
|
import { readFileSync } from "node:fs";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
export const DEFAULT_DAILY_CLUES_PATH = fileURLToPath(new URL("./content/daily-clues.json", import.meta.url));
|
|
|
|
// Indices facultatifs, dans leur ordre d'affichage : un par essai raté, dans l'ordre que choisit le joueur.
|
|
export const DAILY_HINTS = Object.freeze(["album", "collection", "theme", "shape", "page"]);
|
|
|
|
const SUBJECT_ID_PATTERN = /^[a-z0-9-]+(\/[a-z0-9-]+)*$/;
|
|
const THEME_ID_PATTERN = /^[a-z0-9-]+$/;
|
|
// Une branche plus fournie ne renseigne plus assez : elle est à découper.
|
|
export const MAX_SUBJECT_CARDS = 15;
|
|
const MAX_WORDS_IN_EXPRESSION = 3;
|
|
// Petits mots laissés lisibles dans le nom à trous et jamais masqués dans la description.
|
|
const SMALL_WORDS = new Set(["de", "du", "la", "le", "les", "des", "l", "d", "un", "une", "a", "au", "aux", "et", "en", "qui"]);
|
|
const ARTICLES = new Set(["le", "la", "les", "l"]);
|
|
|
|
function plain(text) {
|
|
return text.normalize("NFD").replace(/\p{Diacritic}/gu, "").replace(/œ/gi, "oe").toLowerCase();
|
|
}
|
|
const tokens = (text) => plain(text).match(/[a-z0-9]+/g) || [];
|
|
// Mots d'un nom avec leur place dans le texte d'origine.
|
|
const placedTokens = (text) => [...text.matchAll(/[\p{L}\p{N}]+/gu)].map((match) => ({ key: plain(match[0]), start: match.index, end: match.index + match[0].length }));
|
|
|
|
// Table « suite de mots → thème ». Un mot ne désigne jamais deux thèmes.
|
|
function wordTable(themes, field) {
|
|
const table = new Map();
|
|
for (const theme of themes) {
|
|
for (const entry of theme[field] || []) {
|
|
const key = tokens(entry).join(" ");
|
|
if (!key || key.split(" ").length > MAX_WORDS_IN_EXPRESSION) throw new TypeError(`Daily theme ${theme.id}: « ${entry} » must hold 1 to ${MAX_WORDS_IN_EXPRESSION} words.`);
|
|
if (table.has(key)) throw new TypeError(`Daily theme ${theme.id}: « ${entry} » already belongs to ${table.get(key)}.`);
|
|
table.set(key, theme.id);
|
|
}
|
|
}
|
|
return table;
|
|
}
|
|
|
|
// Premier thème rencontré en lisant les mots, l'expression la plus longue d'abord (« voie lactée » avant « lactée »), et sa place.
|
|
function firstTheme(words, table) {
|
|
for (let start = 0; start < words.length; start += 1) {
|
|
for (let size = Math.min(MAX_WORDS_IN_EXPRESSION, words.length - start); size > 0; size -= 1) {
|
|
const found = words.slice(start, start + size);
|
|
const theme = table.get(found.map((word) => word.key).join(" "));
|
|
if (theme) return { id: theme, span: [found[0].start, found.at(-1).end] };
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// Le thème vient des mots du nom, toujours le même pour un même mot. Le sujet (« Renardeau ») ne compte qu'à défaut : d'abord les
|
|
// mots du thème, puis ses mots faibles, trop répandus pour l'emporter (« astral », ou le personnage d'une constellation).
|
|
function themeReader(content) {
|
|
const strong = wordTable(content.themes, "words");
|
|
const weak = wordTable(content.themes, "weakWords");
|
|
const compounds = content.compoundSubjects.map(tokens).sort((left, right) => right.length - left.length);
|
|
return (name) => {
|
|
let words = placedTokens(name);
|
|
if (ARTICLES.has(words[0]?.key)) words = words.slice(1);
|
|
const subjectLength = compounds.find((compound) => compound.every((word, index) => words[index]?.key === word))?.length ?? 1;
|
|
const rest = words.slice(subjectLength);
|
|
return firstTheme(rest, strong) || firstTheme(rest, weak) || firstTheme(words.slice(0, subjectLength), strong);
|
|
};
|
|
}
|
|
|
|
function requireLabelled(items, pattern, name) {
|
|
const ids = new Set();
|
|
for (const item of items) {
|
|
if (!pattern.test(item?.id ?? "") || typeof item.label !== "string" || !item.label) throw new TypeError(`Daily ${name} ${item?.id ?? "?"} needs an id and a label.`);
|
|
if (ids.has(item.id)) throw new TypeError(`Daily ${name} ${item.id} is declared twice.`);
|
|
ids.add(item.id);
|
|
}
|
|
return ids;
|
|
}
|
|
|
|
// Phrases propres à un sujet, à la place de celles du site : tout ou rien, et chacune nomme le sujet.
|
|
const SENTENCE_KEYS = ["same", "different", "but"];
|
|
function requireSubjectTexts(subject) {
|
|
if (typeof subject.phrase !== "string" || !/^une? /.test(subject.phrase)) throw new TypeError(`Daily subject ${subject.id} needs a phrase starting with « un » or « une ».`);
|
|
if (subject.sentences && !SENTENCE_KEYS.every((key) => subject.sentences[key]?.includes("{subject}"))) throw new TypeError(`Daily subject ${subject.id} needs sentences that name it: ${SENTENCE_KEYS.join(", ")}.`);
|
|
}
|
|
|
|
// Contenu prêt à l'emploi : libellés, chemin du sujet de chaque carte, lecture du thème et mots de recherche.
|
|
export function prepareDailyClues(content) {
|
|
const subjectIds = requireLabelled(content.subjects, SUBJECT_ID_PATTERN, "subject");
|
|
for (const id of subjectIds) {
|
|
const parent = id.split("/").slice(0, -1).join("/");
|
|
if (parent && !subjectIds.has(parent)) throw new TypeError(`Daily subject ${id} has no parent ${parent}.`);
|
|
}
|
|
content.subjects.forEach(requireSubjectTexts);
|
|
requireLabelled(content.themes, THEME_ID_PATTERN, "theme");
|
|
for (const [cardId, clues] of Object.entries(content.cards)) {
|
|
if (!subjectIds.has(clues.subject)) throw new TypeError(`Daily clues of ${cardId} use an unknown subject ${clues.subject}.`);
|
|
if (clues.search != null && (!Array.isArray(clues.search) || clues.search.some((word) => typeof word !== "string" || !word.trim()))) throw new TypeError(`Daily clues of ${cardId} need search words.`);
|
|
}
|
|
const themeMatch = themeReader(content);
|
|
return {
|
|
subjects: new Map(content.subjects.map(({ id, ...step }) => [id, step])),
|
|
themeLabels: new Map(content.themes.map((theme) => [theme.id, theme.label])),
|
|
cards: content.cards,
|
|
themeMatch,
|
|
themeOf: (name) => themeMatch(name)?.id ?? null
|
|
};
|
|
}
|
|
|
|
export function loadDailyClues(path = DEFAULT_DAILY_CLUES_PATH) {
|
|
return prepareDailyClues(JSON.parse(readFileSync(path, "utf8")));
|
|
}
|
|
|
|
// Ce qui manque au catalogue pour que chaque carte ait ses indices. Vérifié par les tests, pas au démarrage : une carte sans
|
|
// sujet ni thème reste jouable, sans comparaison.
|
|
export function dailyCluesIssues(catalog, clues) {
|
|
const cardIds = new Set(catalog.cards.map((card) => card.id));
|
|
const counts = new Map();
|
|
const issues = [];
|
|
for (const card of catalog.cards) {
|
|
const subject = clues.cards[card.id]?.subject;
|
|
if (!subject) issues.push(`${card.id}: no subject`);
|
|
else counts.set(subject, (counts.get(subject) || 0) + 1);
|
|
if (!clues.themeOf(card.name)) issues.push(`${card.id}: no theme for « ${card.name} »`);
|
|
}
|
|
for (const cardId of Object.keys(clues.cards)) if (!cardIds.has(cardId)) issues.push(`${cardId}: unknown card`);
|
|
for (const [subject, count] of counts) if (count > MAX_SUBJECT_CARDS) issues.push(`${subject}: ${count} cards, to split`);
|
|
return issues;
|
|
}
|
|
|
|
// Étapes du sujet d'une carte, de la famille à l'espèce, et thème de son nom.
|
|
function subjectSteps(clues, card) {
|
|
const path = clues.cards[card.id]?.subject?.split("/") || [];
|
|
return path.map((_, index) => clues.subjects.get(path.slice(0, index + 1).join("/")));
|
|
}
|
|
function themeView(clues, card) {
|
|
const match = clues.themeMatch(card.name);
|
|
return match && { label: clues.themeLabels.get(match.id), span: match.span };
|
|
}
|
|
|
|
// Comparaison d'un essai. Sujet : les étapes communes aux deux chemins, puis la première qui diffère, jamais le reste du chemin
|
|
// de la réponse (ni sa longueur). Thème : celui de l'essai, le mot de son nom qui le donne, et s'il est celui de la réponse.
|
|
export function compareClues(clues, answer, guess) {
|
|
const mine = subjectSteps(clues, answer);
|
|
const theirs = subjectSteps(clues, guess);
|
|
let common = 0;
|
|
while (common < mine.length && common < theirs.length && mine[common] === theirs[common]) common += 1;
|
|
const theme = themeView(clues, guess);
|
|
return {
|
|
subject: { common: theirs.slice(0, common), different: theirs[common] ?? null },
|
|
theme: theme && { ...theme, same: clues.themeOf(guess.name) === clues.themeOf(answer.name) }
|
|
};
|
|
}
|
|
|
|
// Indices complets de la réponse, pour la fin de partie.
|
|
export function answerClues(clues, answer) {
|
|
return { subject: subjectSteps(clues, answer), theme: themeView(clues, answer) };
|
|
}
|
|
|
|
const textParts = (text) => text.split(/([\p{L}\p{N}]+)/u).filter(Boolean);
|
|
const isWord = (part) => /[\p{L}\p{N}]/u.test(part);
|
|
|
|
// Deux mots de la même famille : au singulier ou au pluriel, ou presque tout en commun (« patineuse » et « patine »).
|
|
function sameFamily(left, right) {
|
|
const first = left.replace(/[sx]$/, "");
|
|
const second = right.replace(/[sx]$/, "");
|
|
if (first === second) return true;
|
|
let length = 0;
|
|
while (length < first.length && length < second.length && first[length] === second[length]) length += 1;
|
|
return length >= 5 && length >= Math.min(first.length, second.length) - 1;
|
|
}
|
|
|
|
// Un mot caché n'est jamais envoyé : il devient un morceau sans texte.
|
|
const hide = (parts) => parts.map(({ text, hidden }) => (hidden ? { hidden: true } : { text }));
|
|
|
|
// Description partielle : sa première phrase, sans les mots de la famille de ceux du nom.
|
|
export function partialDescription(card) {
|
|
const sentence = card.description.match(/^.*?[.!?…]+(?=\s|$)/s)?.[0] || card.description;
|
|
const names = tokens(card.name).filter((word) => word.length > 2 && !SMALL_WORDS.has(word));
|
|
return hide(textParts(sentence).map((text) => {
|
|
const word = plain(text);
|
|
return { text, hidden: word.length > 2 && !SMALL_WORDS.has(word) && names.some((name) => sameFamily(name, word)) };
|
|
}));
|
|
}
|
|
|
|
// Nom à trous : ses petits mots et sa ponctuation, sans la longueur des autres mots.
|
|
export function nameShape(name) {
|
|
return hide(textParts(name).map((text) => ({ text, hidden: isWord(text) && !SMALL_WORDS.has(plain(text)) })));
|
|
}
|
|
|
|
// Un indice par essai raté, au choix.
|
|
export function dailyHintCredits(wrongCount, usedCount) {
|
|
return Math.max(0, Math.min(wrongCount, DAILY_HINTS.length) - usedCount);
|
|
}
|
|
|
|
// `known` : indices qui n'apprendraient rien au joueur (un thème qu'un essai a déjà trouvé).
|
|
export function canUseDailyHint(hintId, wrongCount, used, known = []) {
|
|
return DAILY_HINTS.includes(hintId) && !known.includes(hintId) && !used.includes(hintId) && dailyHintCredits(wrongCount, used.length) > 0;
|
|
}
|