279 lines
16 KiB
JavaScript
279 lines
16 KiB
JavaScript
/**
|
||
* @file Règles pures de l'Équipe du jour : spécialités, personnages proposés, étoiles, recrutement, durée d'une
|
||
* équipe.
|
||
*
|
||
* Utilisé par : team-service.js, team-race.js, team-settings.js, mirror-service.js, service.js,
|
||
* scripts/team-specialties.mjs.
|
||
* Attention : aucune fonction ne lit la base ni l'horloge ; les services les appliquent avec la base.
|
||
* @see docs/equipe-du-jour.md
|
||
*/
|
||
|
||
import { randomInt } from "node:crypto";
|
||
import { isDestinationCard } from "./catalog.js";
|
||
import { cardRarity, shiftDayKey } from "./daily.js";
|
||
import { STAT_IDS, splitPower } from "./expedition-rules.js";
|
||
|
||
export const TEAM_SIZE = 5;
|
||
export const OFFER_SIZE = 3;
|
||
// Jours d'utilisation d'une équipe, jour du recrutement compris.
|
||
export const TEAM_DAYS = 3;
|
||
export const MAX_GOLD_RESERVE = 3;
|
||
// Une collection qui a moins de personnages d'une spécialité est complétée par des personnages prêtés.
|
||
export const MIN_SPECIALISTS = 3;
|
||
// Écart entre la plus haute et la plus basse stat d'un profil jusqu'auquel il est « Équilibré », en points.
|
||
export const BALANCED_SPREAD = 10;
|
||
export const STAR_KINDS = Object.freeze(["gold", "black", "dust"]);
|
||
|
||
export const DEFAULT_TEAM_SETTINGS = Object.freeze({
|
||
goldStars: 8, blackStars: 3, dustStars: 2, dustValue: 3,
|
||
// Fois où le joueur peut redemander trois personnages, par recrutement.
|
||
rerolls: 2,
|
||
// Puissance à l'arrivée, puis après chaque étoile dorée ; `fallPower` après une étoile noire.
|
||
powers: Object.freeze([50, 60, 75, 95]), fallPower: 30
|
||
});
|
||
|
||
const defaultRandom = (max) => randomInt(max);
|
||
|
||
/** Copie mélangée (Fisher-Yates). `random(max)` rend un entier de 0 à max - 1 ; les tests le remplacent pour rester reproductibles. */
|
||
export function shuffle(items, random = defaultRandom) {
|
||
const result = [...items];
|
||
for (let index = result.length - 1; index > 0; index -= 1) {
|
||
const other = random(index + 1);
|
||
[result[index], result[other]] = [result[other], result[index]];
|
||
}
|
||
return result;
|
||
}
|
||
|
||
/** Message d'erreur du premier réglage invalide de l'Équipe du jour, ou `null` si tout est valide. */
|
||
export function teamSettingsError(settings) {
|
||
const integer = (value, min, max) => Number.isInteger(value) && value >= min && value <= max;
|
||
if (!settings || typeof settings !== "object" || Array.isArray(settings)) return "Réglages de l’équipe invalides.";
|
||
if (!integer(settings.goldStars, 1, 30)) return "Étoiles dorées : un entier entre 1 et 30.";
|
||
if (!integer(settings.blackStars, 0, 15)) return "Étoiles noires : un entier entre 0 et 15.";
|
||
if (!integer(settings.dustStars, 0, 10)) return "Étoiles de poussière : un entier entre 0 et 10.";
|
||
if (!integer(settings.dustValue, 0, 1_000)) return "Poussière par étoile : un entier entre 0 et 1 000.";
|
||
if (!integer(settings.rerolls, 0, 10)) return "Nouvelles propositions : un entier entre 0 et 10.";
|
||
const { powers, fallPower } = settings;
|
||
if (!Array.isArray(powers) || powers.length < 2 || powers.length > 6 || powers.some((power) => !integer(power, 1, 100))) return "Paliers de Puissance : de 2 à 6 entiers entre 1 et 100.";
|
||
if (powers.some((power, index) => index > 0 && power <= powers[index - 1])) return "Chaque palier de Puissance doit dépasser le précédent.";
|
||
// Une chute au niveau de départ ou au-dessus rendrait le premier essai gratuit.
|
||
if (!integer(fallPower, 1, 100) || fallPower >= powers[0]) return "La Puissance après une étoile noire doit être inférieure à celle du départ.";
|
||
return null;
|
||
}
|
||
|
||
// --- Personnages et spécialités -------------------------------------------------------------------------------------------
|
||
|
||
/**
|
||
* Spécialités d'un profil : deux stats si les deux meilleures sont à égalité, aucune s'il est équilibré ou si trois stats ou plus
|
||
* se partagent la première place (jamais trois pouvoirs, ni une spécialité tirée au hasard parmi elles), sinon la meilleure.
|
||
*/
|
||
export function specialtiesOf(profile) {
|
||
const values = STAT_IDS.map((stat) => profile[stat]);
|
||
const highest = Math.max(...values);
|
||
const best = STAT_IDS.filter((stat) => profile[stat] === highest);
|
||
if (best.length === 2) return best;
|
||
return best.length > 2 || highest - Math.min(...values) <= BALANCED_SPREAD ? [] : [best[0]];
|
||
}
|
||
|
||
/** Clé texte d'un profil de stats (`"40/30/20/10"`), pour regrouper les personnages au même profil. */
|
||
export const profileKey = (profile) => STAT_IDS.map((stat) => profile[stat]).join("/");
|
||
|
||
/**
|
||
* Personnages qui peuvent rejoindre une équipe : ni communes, ni destinations, et illustrés. `active` : sa collection est ouverte,
|
||
* seule condition pour être prêté, afin de ne jamais dévoiler une collection fermée à qui n'en a pas la carte.
|
||
*/
|
||
export function teamCharacters(catalog) {
|
||
const collections = new Map(catalog.collections.map((collection) => [collection.id, collection]));
|
||
return catalog.cards.flatMap((card) => {
|
||
const collection = collections.get(card.collectionId);
|
||
const profile = card.expedition?.profile || collection?.expedition?.profile;
|
||
if (!card.image || !profile || isDestinationCard(card) || card.expedition?.equipment || cardRarity(catalog, card.id) === "common") return [];
|
||
return [{ id: card.id, profile, active: Boolean(collection.active) }];
|
||
});
|
||
}
|
||
|
||
/** Stats d'un équipier : sa Puissance répartie selon les pourcentages de son profil. */
|
||
export const companionStats = (profile, power) => splitPower(power, profile);
|
||
|
||
/** Personnages prêtés à un joueur : de quoi avoir MIN_SPECIALISTS personnages de chaque spécialité. */
|
||
export function lentCharacters(characters, ownedIds, random = defaultRandom) {
|
||
const pool = characters.filter((character) => ownedIds.has(character.id));
|
||
const lent = [];
|
||
for (const stat of STAT_IDS) {
|
||
const has = (character) => specialtiesOf(character.profile).includes(stat);
|
||
const missing = MIN_SPECIALISTS - [...pool, ...lent].filter(has).length;
|
||
if (missing > 0) lent.push(...shuffle(characters.filter((character) => character.active && !ownedIds.has(character.id) && !lent.includes(character) && has(character)), random).slice(0, missing));
|
||
}
|
||
return lent.map((character) => character.id);
|
||
}
|
||
|
||
/**
|
||
* Trois personnages de profils différents : d'abord ceux du joueur et ses prêtés pas encore proposés, puis ceux déjà proposés
|
||
* (`excludedIds` : l'équipe et les trois derniers), enfin le reste des collections ouvertes. Un profil porté par beaucoup de
|
||
* personnages n'est pas proposé plus souvent qu'un autre.
|
||
*/
|
||
export function drawOffer(characters, { poolIds, seenIds, excludedIds = seenIds }, random = defaultRandom) {
|
||
const offer = [];
|
||
const used = new Set();
|
||
const take = (candidates, hiddenIds) => {
|
||
const byProfile = new Map();
|
||
for (const character of candidates) {
|
||
const key = profileKey(character.profile);
|
||
if (hiddenIds.has(character.id) || used.has(key)) continue;
|
||
byProfile.set(key, [...(byProfile.get(key) || []), character.id]);
|
||
}
|
||
for (const [key, ids] of shuffle([...byProfile], random).slice(0, OFFER_SIZE - offer.length)) {
|
||
used.add(key);
|
||
offer.push(ids[random(ids.length)]);
|
||
}
|
||
};
|
||
const pool = characters.filter((character) => poolIds.has(character.id));
|
||
take(pool, seenIds);
|
||
if (offer.length < OFFER_SIZE) take(pool, new Set([...excludedIds, ...offer]));
|
||
if (offer.length < OFFER_SIZE) take(characters.filter((character) => character.active && !poolIds.has(character.id)), seenIds);
|
||
return offer;
|
||
}
|
||
|
||
// --- Recrutement ----------------------------------------------------------------------------------------------------------
|
||
|
||
/** État d'un recrutement, enregistré tel quel : `sky` (étoiles dans l'ordre affiché) ne doit jamais partir au client. */
|
||
export function startRecruitment(characters, { ownedIds, goldReserve = 0, settings = DEFAULT_TEAM_SETTINGS }, random = defaultRandom) {
|
||
const extra = Math.min(MAX_GOLD_RESERVE, Math.max(0, goldReserve));
|
||
const sky = shuffle([
|
||
...Array(settings.goldStars + extra).fill("gold"),
|
||
...Array(settings.blackStars).fill("black"),
|
||
...Array(settings.dustStars).fill("dust")
|
||
], random);
|
||
const state = { settings, extraGold: extra, sky, revealed: [], lentIds: lentCharacters(characters, ownedIds, random), seenIds: [], offer: [], current: null, team: [], dust: 0, rerolls: settings.rerolls };
|
||
return nextOffer(characters, ownedIds, state, random);
|
||
}
|
||
|
||
function nextOffer(characters, ownedIds, state, random) {
|
||
const poolIds = new Set([...ownedIds, ...state.lentIds]);
|
||
const excludedIds = new Set([...state.team.map((companion) => companion.cardId), ...state.offer]);
|
||
const offer = drawOffer(characters, { poolIds, seenIds: new Set(state.seenIds), excludedIds }, random);
|
||
return { ...state, offer, seenIds: [...state.seenIds, ...offer], current: null };
|
||
}
|
||
|
||
/**
|
||
* Un personnage proposé ou choisi a pu quitter le catalogue pendant le recrutement : les propositions sont alors refaites, sans
|
||
* toucher au ciel ni à l'équipe. Sinon, l'état est renvoyé tel quel.
|
||
*/
|
||
export function repairRecruitment(characters, ownedIds, state, random = defaultRandom) {
|
||
if (recruitmentFinished(state)) return state;
|
||
const known = new Set(characters.map((character) => character.id));
|
||
const broken = state.current ? !known.has(state.current.cardId) : state.offer.some((id) => !known.has(id));
|
||
return broken ? nextOffer(characters, ownedIds, state, random) : state;
|
||
}
|
||
|
||
/** Vrai quand l'équipe est complète : plus de recrutement possible. */
|
||
export const recruitmentFinished = (state) => state.team.length >= TEAM_SIZE;
|
||
|
||
/** Remplace les trois personnages proposés, tant qu'il reste de nouvelles propositions. */
|
||
export function rerollOffer(characters, ownedIds, state, random = defaultRandom) {
|
||
if (state.current || recruitmentFinished(state) || !(state.rerolls > 0)) return null;
|
||
return { ...nextOffer(characters, ownedIds, state, random), rerolls: state.rerolls - 1 };
|
||
}
|
||
|
||
/** Nouvel état après le choix d'un personnage parmi ceux proposés, ou `null` si ce choix n'est pas permis. */
|
||
export function chooseCharacter(state, cardId) {
|
||
if (state.current || recruitmentFinished(state) || !state.offer.includes(cardId)) return null;
|
||
return { ...state, current: { cardId, step: 0, power: state.settings.powers[0], fallen: false } };
|
||
}
|
||
|
||
/**
|
||
* Vrai si le joueur peut retourner l'étoile `index` : un personnage est en cours, n'est pas tombé, n'a pas atteint le dernier palier, et
|
||
* l'étoile est encore cachée.
|
||
*/
|
||
export function canRevealStar(state, index) {
|
||
const { current, settings } = state;
|
||
return Boolean(current) && !current.fallen && current.step < settings.powers.length - 1
|
||
&& Number.isInteger(index) && index >= 0 && index < state.sky.length && !state.revealed.includes(index);
|
||
}
|
||
|
||
/** Retourne l'étoile choisie. `dust` de l'état cumule la poussière trouvée ; `star` dit ce qui vient d'être retourné. */
|
||
export function revealStar(state, index) {
|
||
if (!canRevealStar(state, index)) return null;
|
||
const { settings, current } = state;
|
||
const star = state.sky[index];
|
||
const revealed = [...state.revealed, index];
|
||
if (star === "dust") return { star, state: { ...state, revealed, dust: state.dust + settings.dustValue } };
|
||
if (star === "black") return { star, state: { ...state, revealed, current: { ...current, power: settings.fallPower, fallen: true } } };
|
||
const step = current.step + 1;
|
||
return { star, state: { ...state, revealed, current: { ...current, step, power: settings.powers[step] } } };
|
||
}
|
||
|
||
/** Soin d'un compagnon affaibli, avant de le garder : il retrouve sa Puissance de départ, sans nouvel essai. */
|
||
export function healCompanion(state) {
|
||
const { current, settings } = state;
|
||
if (!current?.fallen || current.healed) return null;
|
||
return { ...state, current: { ...current, power: settings.powers[0], healed: true } };
|
||
}
|
||
|
||
/**
|
||
* Garde le compagnon en cours et propose les suivants, sauf si l'équipe est complète. Son profil est figé avec lui : un changement du
|
||
* catalogue ne modifie pas une équipe déjà recrutée. `null` sans compagnon en cours, ou s'il n'est plus au catalogue.
|
||
*/
|
||
export function keepCompanion(characters, ownedIds, state, random = defaultRandom) {
|
||
const profile = characters.find((character) => character.id === state.current?.cardId)?.profile;
|
||
if (!profile) return null;
|
||
const { cardId, step, power, fallen, healed = false } = state.current;
|
||
const next = { ...state, team: [...state.team, { cardId, profile, power, step, fallen, healed, lent: !ownedIds.has(cardId) }], current: null };
|
||
return recruitmentFinished(next) ? { ...next, offer: [] } : nextOffer(characters, ownedIds, next, random);
|
||
}
|
||
|
||
/** Étoiles encore cachées, par sorte. */
|
||
export function hiddenStars(state) {
|
||
const counts = Object.fromEntries(STAR_KINDS.map((kind) => [kind, 0]));
|
||
state.sky.forEach((kind, index) => { if (!state.revealed.includes(index)) counts[kind] += 1; });
|
||
return counts;
|
||
}
|
||
|
||
/** Ciel visible par le joueur : `null` pour une étoile cachée, sauf à la fin du recrutement où tout est dévoilé. */
|
||
export function visibleSky(state) {
|
||
const all = recruitmentFinished(state);
|
||
return state.sky.map((kind, index) => ({ kind: all || state.revealed.includes(index) ? kind : null, revealed: state.revealed.includes(index) }));
|
||
}
|
||
|
||
// --- Durée d'une équipe ---------------------------------------------------------------------------------------------------
|
||
|
||
/** Rang du jour d'une équipe (1 le jour du recrutement), ou 0 quand elle a servi TEAM_DAYS jours. */
|
||
export function teamDay(recruitedDay, today) {
|
||
for (let offset = 0; offset < TEAM_DAYS; offset += 1) if (shiftDayKey(recruitedDay, offset) === today) return offset + 1;
|
||
return 0;
|
||
}
|
||
|
||
// --- Équipes inventées ----------------------------------------------------------------------------------------------------
|
||
|
||
// Niveaux des « Équipes des Veilleurs » qui complètent une course : part des choix bien faits, en %.
|
||
export const WATCHER_TEAM_LEVELS = Object.freeze({ strong: 90, medium: 60, weak: 30 });
|
||
|
||
/**
|
||
* Joue un recrutement entier. Un choix bien fait prend le personnage le plus utile au parcours et n'améliore que sous 28 % de risque ;
|
||
* un choix mal fait prend un personnage au hasard et s'arrête dès 15 % de risque. `goldReserve` : étoiles dorées ajoutées au ciel,
|
||
* comme la réserve d'un joueur (scripts d'équilibrage ; les Équipes des Veilleurs n'en ont pas).
|
||
*/
|
||
export function inventTeam(characters, zones, skill, random = defaultRandom, settings = DEFAULT_TEAM_SETTINGS, goldReserve = 0) {
|
||
const ownedIds = new Set(characters.filter((character) => character.active).map((character) => character.id));
|
||
const byId = new Map(characters.map((character) => [character.id, character]));
|
||
const needs = [...zones];
|
||
let state = startRecruitment(characters, { ownedIds, goldReserve, settings }, random);
|
||
while (!recruitmentFinished(state) && state.offer.length) {
|
||
const good = random(100) < skill;
|
||
const worth = (id) => Math.max(...needs.map((stat) => byId.get(id).profile[stat]));
|
||
const cardId = good ? [...state.offer].sort((left, right) => worth(right) - worth(left))[0] : state.offer[random(state.offer.length)];
|
||
const served = [...needs].sort((left, right) => byId.get(cardId).profile[right] - byId.get(cardId).profile[left])[0];
|
||
if (needs.length > 1) needs.splice(needs.indexOf(served), 1);
|
||
state = chooseCharacter(state, cardId);
|
||
const limit = random(100) < skill ? 28 : 15;
|
||
for (;;) {
|
||
const hidden = state.sky.flatMap((_, index) => (state.revealed.includes(index) ? [] : [index]));
|
||
if (!hidden.length || hiddenStars(state).black * 100 > limit * hidden.length) break;
|
||
const result = revealStar(state, hidden[random(hidden.length)]);
|
||
if (!result) break;
|
||
state = result.state;
|
||
}
|
||
state = keepCompanion(characters, ownedIds, state, random);
|
||
}
|
||
return state.team;
|
||
}
|