Add the rules, storage and API of the daily team and its race
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
880f007cce
commit
71cf739a2e
23 changed files with 1703 additions and 15 deletions
|
|
@ -325,12 +325,62 @@ export function createCardsApiHandler({
|
|||
json(res, 200, service.guessDaily(session.player.id, { day: body.day, cardId: body.cardId }));
|
||||
return true;
|
||||
}
|
||||
if (req.method === "POST" && url.pathname === "/api/cards/daily/reward") {
|
||||
rateLimit(req, "daily-reward", 30);
|
||||
const body = await readBody(req);
|
||||
json(res, 200, service.chooseDailyReward(session.player.id, { day: body.day, choice: body.choice }));
|
||||
return true;
|
||||
}
|
||||
if (req.method === "POST" && url.pathname === "/api/cards/daily/hints") {
|
||||
rateLimit(req, "daily-hint", 30);
|
||||
const body = await readBody(req);
|
||||
json(res, 200, { daily: service.useDailyHint(session.player.id, { day: body.day, hint: body.hint }) });
|
||||
return true;
|
||||
}
|
||||
if (req.method === "GET" && url.pathname === "/api/cards/team") {
|
||||
json(res, 200, { team: service.team.view(session.player.id) });
|
||||
return true;
|
||||
}
|
||||
if (req.method === "POST" && url.pathname === "/api/cards/team/recruit") {
|
||||
rateLimit(req, "team-recruit", 30);
|
||||
json(res, 200, service.team.startRecruitment(session.player.id, { day: (await readBody(req)).day }));
|
||||
return true;
|
||||
}
|
||||
if (req.method === "POST" && url.pathname === "/api/cards/team/choose") {
|
||||
rateLimit(req, "team-choose", 60);
|
||||
json(res, 200, service.team.chooseCharacter(session.player.id, { cardId: (await readBody(req)).cardId }));
|
||||
return true;
|
||||
}
|
||||
if (req.method === "POST" && url.pathname === "/api/cards/team/stars") {
|
||||
rateLimit(req, "team-stars", 120);
|
||||
json(res, 200, service.team.revealStar(session.player.id, { index: (await readBody(req)).index }));
|
||||
return true;
|
||||
}
|
||||
if (req.method === "POST" && url.pathname === "/api/cards/team/keep") {
|
||||
rateLimit(req, "team-keep", 60);
|
||||
json(res, 200, service.team.keepCompanion(session.player.id, { cardId: (await readBody(req)).cardId }));
|
||||
return true;
|
||||
}
|
||||
if (req.method === "POST" && url.pathname === "/api/cards/team/race") {
|
||||
rateLimit(req, "race-start", 30);
|
||||
const body = await readBody(req);
|
||||
json(res, 200, service.team.startRace(session.player.id, { day: body.day, cardId: body.cardId }));
|
||||
return true;
|
||||
}
|
||||
if (req.method === "POST" && url.pathname === "/api/cards/team/race/boosts") {
|
||||
rateLimit(req, "race-boosts", 120);
|
||||
json(res, 200, service.team.recordBoosts(session.player.id, { boosts: (await readBody(req)).boosts }));
|
||||
return true;
|
||||
}
|
||||
if (req.method === "POST" && url.pathname === "/api/cards/team/race/finish") {
|
||||
rateLimit(req, "race-finish", 60);
|
||||
json(res, 200, service.team.finishRace(session.player.id, { boosts: (await readBody(req)).boosts }));
|
||||
return true;
|
||||
}
|
||||
if (req.method === "PUT" && url.pathname === "/api/cards/admin/team/settings") {
|
||||
json(res, 200, service.team.updateSettings(session.player.id, (await readBody(req)).settings));
|
||||
return true;
|
||||
}
|
||||
if (req.method === "GET" && url.pathname === "/api/cards/expeditions") {
|
||||
json(res, 200, service.expeditions.getExpeditions(session.player.id));
|
||||
return true;
|
||||
|
|
|
|||
|
|
@ -522,6 +522,48 @@ export const MIGRATIONS = [
|
|||
`
|
||||
UPDATE daily_attempts SET hints_json = (SELECT json_group_array(hint.value) FROM json_each(daily_attempts.hints_json) AS hint WHERE hint.value <> 'rarity')
|
||||
WHERE EXISTS (SELECT 1 FROM json_each(daily_attempts.hints_json) AS hint WHERE hint.value = 'rarity');
|
||||
`,
|
||||
// Équipe du jour : réserve d'étoiles dorées, réglages (fermée au départ), parcours du jour et équipe de chaque joueur, recrutement
|
||||
// en cours compris (`ready_day` NULL jusqu'à ce que l'équipe soit complète).
|
||||
`
|
||||
ALTER TABLE players ADD COLUMN gold_stars INTEGER NOT NULL DEFAULT 0 CHECK (gold_stars BETWEEN 0 AND 3);
|
||||
CREATE TABLE team_settings (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
settings_json TEXT NOT NULL CHECK (json_valid(settings_json)),
|
||||
updated_at INTEGER NOT NULL,
|
||||
updated_by TEXT REFERENCES players(id)
|
||||
) STRICT;
|
||||
INSERT INTO team_settings(id, settings_json, updated_at, updated_by) VALUES (1, '{}', 0, NULL);
|
||||
CREATE TABLE team_days (
|
||||
day TEXT PRIMARY KEY,
|
||||
zones_json TEXT NOT NULL CHECK (json_valid(zones_json)),
|
||||
created_at INTEGER NOT NULL
|
||||
) STRICT;
|
||||
CREATE TABLE player_teams (
|
||||
player_id TEXT PRIMARY KEY REFERENCES players(id) ON DELETE CASCADE,
|
||||
started_day TEXT NOT NULL,
|
||||
ready_day TEXT,
|
||||
state_json TEXT NOT NULL CHECK (json_valid(state_json)),
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
) STRICT;
|
||||
`,
|
||||
// Course des courants : une course par joueur et par jour, avec ses adversaires figés au départ. Carte du jour : récompense au choix
|
||||
// d'une victoire (montants proposés, puis choix du joueur ; NULL pour une victoire payée d'office).
|
||||
`
|
||||
CREATE TABLE team_races (
|
||||
player_id TEXT NOT NULL REFERENCES players(id) ON DELETE CASCADE,
|
||||
day TEXT NOT NULL,
|
||||
status TEXT NOT NULL CHECK (status IN ('running', 'finished')),
|
||||
started_at INTEGER NOT NULL,
|
||||
race_json TEXT NOT NULL CHECK (json_valid(race_json)),
|
||||
boosts_json TEXT NOT NULL CHECK (json_valid(boosts_json)),
|
||||
place INTEGER,
|
||||
reward INTEGER NOT NULL DEFAULT 0 CHECK (reward >= 0),
|
||||
PRIMARY KEY (player_id, day)
|
||||
) STRICT;
|
||||
ALTER TABLE daily_attempts ADD COLUMN reward_offer_json TEXT CHECK (reward_offer_json IS NULL OR json_valid(reward_offer_json));
|
||||
ALTER TABLE daily_attempts ADD COLUMN reward_choice TEXT CHECK (reward_choice IS NULL OR reward_choice IN ('pending', 'stardust', 'star'));
|
||||
`
|
||||
];
|
||||
|
||||
|
|
|
|||
129
services/cards/race-rules.js
Normal file
129
services/cards/race-rules.js
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
// Rôle : règles pures de la Course des courants (parcours, déroulement, élans, adversaires, classement).
|
||||
// Sans dépendance : le service recalcule une course avec ce module, et la page peut l'animer avec le même.
|
||||
// Temps en millisecondes, avancés par pas fixes : les mêmes élans donnent toujours le même résultat. Règles : docs/equipe-du-jour.md.
|
||||
|
||||
export const RACE_STATS = Object.freeze(["bravoure", "endurance", "fortune", "orientation"]);
|
||||
export const ZONE_COUNT = 8;
|
||||
// Répartition des zones : une stat 3 fois, deux stats 2 fois, la dernière 1 fois.
|
||||
const ZONE_SHARES = Object.freeze([3, 2, 2, 1]);
|
||||
export const ZONE_LENGTH = 70;
|
||||
export const RACE_LENGTH = ZONE_COUNT * ZONE_LENGTH;
|
||||
export const RACERS = 4;
|
||||
const BASE_SPEED = 14;
|
||||
export const BOOST_MS = 1_500;
|
||||
export const BOOST_FACTOR = 1.5;
|
||||
export const STEP_MS = 10;
|
||||
// Vitesse minimale : BASE_SPEED. Une course dure donc au plus RACE_LENGTH / BASE_SPEED secondes.
|
||||
export const MAX_RACE_MS = Math.ceil(RACE_LENGTH / BASE_SPEED) * 1_000;
|
||||
export const RACE_REWARDS = Object.freeze([20, 15, 10, 5]);
|
||||
|
||||
// `random(max)` renvoie un entier dans [0, max).
|
||||
export function drawZones(random) {
|
||||
const draw = (items) => {
|
||||
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;
|
||||
};
|
||||
return draw(draw(RACE_STATS).flatMap((stat, index) => Array(ZONE_SHARES[index]).fill(stat)));
|
||||
}
|
||||
|
||||
export const zoneAt = (position) => Math.min(ZONE_COUNT - 1, Math.floor(position / ZONE_LENGTH));
|
||||
export const runnerSpeed = (runner, stat) => BASE_SPEED + runner[stat];
|
||||
export const boostSpeed = (helper, stat) => helper[stat] * BOOST_FACTOR;
|
||||
|
||||
// Le coureur le plus rapide sans élan : celui que prennent les équipes jouées automatiquement.
|
||||
export function bestRunner(companions, zones) {
|
||||
const time = (stats) => zones.reduce((sum, stat) => sum + 1 / runnerSpeed(stats, stat), 0);
|
||||
return companions.reduce((best, stats, index) => (time(stats) < time(companions[best]) ? index : best), 0);
|
||||
}
|
||||
|
||||
// État d'un coureur ; `helpers` sont les stats de ses équipiers, `used` ceux qui ont déjà donné leur élan.
|
||||
export const startRun = () => ({ time: 0, position: 0, used: [], boostEnd: 0, boostSpeed: 0, boosts: [], finishedAt: null });
|
||||
|
||||
export const canBoost = (run, helpers, helper) => run.finishedAt === null && run.time >= run.boostEnd
|
||||
&& Number.isInteger(helper) && helper >= 0 && helper < helpers.length && !run.used.includes(helper);
|
||||
|
||||
// Donne l'élan d'un équipier, à la stat de la zone où se trouve le coureur ; rien ne change s'il n'est pas permis.
|
||||
export function applyBoost(run, helpers, zones, helper) {
|
||||
if (!canBoost(run, helpers, helper)) return run;
|
||||
return {
|
||||
...run, used: [...run.used, helper], boostEnd: run.time + BOOST_MS,
|
||||
boostSpeed: boostSpeed(helpers[helper], zones[zoneAt(run.position)]), boosts: [...run.boosts, { at: run.time, helper }]
|
||||
};
|
||||
}
|
||||
|
||||
// Avance d'un pas. L'arrivée est datée à la milliseconde près, pour départager deux coureurs arrivés dans le même pas.
|
||||
export function stepRun(run, runner, zones) {
|
||||
if (run.finishedAt !== null) return run;
|
||||
const speed = runnerSpeed(runner, zones[zoneAt(run.position)]) + (run.time < run.boostEnd ? run.boostSpeed : 0);
|
||||
const position = run.position + (speed * STEP_MS) / 1_000;
|
||||
const time = run.time + STEP_MS;
|
||||
if (position < RACE_LENGTH) return { ...run, position, time };
|
||||
const finishedAt = Math.round(run.time + ((RACE_LENGTH - run.position) / speed) * 1_000);
|
||||
return { ...run, position: RACE_LENGTH, time, finishedAt };
|
||||
}
|
||||
|
||||
// Rejoue une course à partir des élans demandés. Un élan impossible (équipier déjà pris, élan en cours, course finie) est ignoré.
|
||||
export function replayRun({ runner, helpers, boosts = [] }, zones) {
|
||||
const queue = [...boosts].sort((left, right) => left.at - right.at);
|
||||
let run = startRun();
|
||||
while (run.finishedAt === null) {
|
||||
while (queue.length && queue[0].at <= run.time) run = applyBoost(run, helpers, zones, queue.shift().helper);
|
||||
run = stepRun(run, runner, zones);
|
||||
}
|
||||
return run;
|
||||
}
|
||||
|
||||
// Élans demandés par le client : une liste courte d'instants et d'équipiers. Renvoie un message d'erreur, ou null.
|
||||
export function boostsError(boosts, helperCount) {
|
||||
if (!Array.isArray(boosts) || boosts.length > helperCount) return "Élans invalides.";
|
||||
const valid = boosts.every((boost) => Number.isInteger(boost?.at) && boost.at >= 0 && boost.at <= MAX_RACE_MS && Number.isInteger(boost.helper) && boost.helper >= 0 && boost.helper < helperCount);
|
||||
if (!valid || new Set(boosts.map((boost) => boost.helper)).size !== boosts.length) return "Élans invalides.";
|
||||
return null;
|
||||
}
|
||||
|
||||
// Course jouée automatiquement. `skilled` garde chaque équipier pour la zone restante qui lui va le mieux ; sinon, les élans partent
|
||||
// à des instants tirés au hasard. Renvoie les élans donnés et l'arrivée.
|
||||
export function autoRun({ runner, helpers }, zones, skilled, random) {
|
||||
const order = skilled ? [] : helpers.map((_, index) => index);
|
||||
const times = order.map(() => 800 + random(12_000)).sort((left, right) => left - right);
|
||||
for (let index = order.length - 1; index > 0; index -= 1) {
|
||||
const other = random(index + 1);
|
||||
[order[index], order[other]] = [order[other], order[index]];
|
||||
}
|
||||
let run = startRun();
|
||||
while (run.finishedAt === null) {
|
||||
if (run.time >= run.boostEnd) {
|
||||
if (!skilled) {
|
||||
if (times.length && run.time >= times[0]) {
|
||||
times.shift();
|
||||
run = applyBoost(run, helpers, zones, order.shift());
|
||||
}
|
||||
} else {
|
||||
const choice = skilledBoost(run, helpers, zones);
|
||||
if (choice !== null) run = applyBoost(run, helpers, zones, choice);
|
||||
}
|
||||
}
|
||||
run = stepRun(run, runner, zones);
|
||||
}
|
||||
return run;
|
||||
}
|
||||
|
||||
function skilledBoost(run, helpers, zones) {
|
||||
const zone = zoneAt(run.position);
|
||||
const stat = zones[zone];
|
||||
const available = helpers.flatMap((_, index) => (run.used.includes(index) ? [] : [index]));
|
||||
if (!available.length) return null;
|
||||
const strongest = (indexes) => indexes.reduce((best, index) => (helpers[index][stat] > helpers[best][stat] ? index : best), indexes[0]);
|
||||
if (zone === ZONE_COUNT - 1) return strongest(available);
|
||||
// En fin de zone, l'élan se perdrait en partie dans la suivante.
|
||||
if (run.position % ZONE_LENGTH > ZONE_LENGTH * 0.45) return null;
|
||||
const ready = available.filter((index) => zones.slice(zone).every((later) => helpers[index][stat] >= helpers[index][later]));
|
||||
return ready.length ? strongest(ready) : null;
|
||||
}
|
||||
|
||||
// Place du joueur (1 à RACERS) : à égalité, il passe devant.
|
||||
export const placeOf = (finishedAt, others) => 1 + others.filter((other) => other < finishedAt).length;
|
||||
|
|
@ -8,6 +8,8 @@ import { answerClues, canUseDailyHint, compareClues, DAILY_HINTS, dailyHintCredi
|
|||
import { calculateRecharge, pinnedRecharge, drawPack, drawShopPack, MAX_RECHARGE_INTERVAL_MS, MAX_RESERVE_OPENINGS, MIN_RECHARGE_INTERVAL_MS, spendOpening } from "./game-rules.js";
|
||||
import { DEFAULT_DESTINATIONS_PATH, loadExpeditionDestinations } from "./expedition-content.js";
|
||||
import { ExpeditionService } from "./expedition-service.js";
|
||||
import { MAX_GOLD_RESERVE } from "./team-rules.js";
|
||||
import { TeamService } from "./team-service.js";
|
||||
|
||||
const TRANSFER_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
|
|
@ -40,7 +42,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", "card_upgraded", "eclats_converted", "item_used", "destination_starter", "card_plan_changed", "item_bought"
|
||||
"gift_created", "gift_joined", "gift_completed", "gift_cancelled", "daily_won", "expedition_completed", "expedition_cancelled_by_guild", "expedition_dissolved", "card_upgraded", "eclats_converted", "item_used", "destination_starter", "card_plan_changed", "item_bought", "team_recruited", "race_finished", "daily_reward_chosen"
|
||||
]);
|
||||
const DEV_STARDUST = 1000;
|
||||
const DELETED_PLAYER_NAME = "Joueur supprimé";
|
||||
|
|
@ -84,6 +86,7 @@ export class CardsService {
|
|||
this.random = random ?? ((max) => randomInt(max));
|
||||
this.dailyClues = dailyClues || loadDailyClues();
|
||||
this.reloadCatalog();
|
||||
this.team = new TeamService(this);
|
||||
this.expeditions = new ExpeditionService(this, destinations || loadExpeditionDestinations(DEFAULT_DESTINATIONS_PATH, catalog), alerts);
|
||||
}
|
||||
|
||||
|
|
@ -640,7 +643,10 @@ export class CardsService {
|
|||
buildState(playerId) {
|
||||
// Groupes arrivés au bout de leur inscription : départ ou dissolution avant de lire l'historique et le résumé.
|
||||
this.expeditions.settleForming();
|
||||
const recharge = this.database.transaction(() => this.refreshRecharge(playerId));
|
||||
const recharge = this.database.transaction(() => {
|
||||
this.settleDailyRewards(playerId);
|
||||
return this.refreshRecharge(playerId);
|
||||
});
|
||||
this.expireTransfers();
|
||||
const player = this.db.prepare("SELECT * FROM players WHERE id = ?").get(playerId);
|
||||
if (!player) fail(404, "PLAYER_NOT_FOUND", "Profil introuvable.");
|
||||
|
|
@ -668,6 +674,7 @@ export class CardsService {
|
|||
// Le Pont des Veilleurs (poussière vers Éclats) est vendu en boutique, au taux réglé dans les Expéditions.
|
||||
shop: { stardustValues: shop.stardustValues, openingPrice: shop.openingPrice, shopPackPrice: shop.shopPackPrice, shopPackShare: shop.shopPackShare, dailyReward: shop.dailyReward, stardustPerEclat: this.expeditions.settings.progression.stardustPerEclat, oblivionPrice: this.expeditions.settings.progression.oblivionPrice, windRosePrice: this.expeditions.settings.progression.windRosePrice },
|
||||
daily: this.dailySummary(playerId),
|
||||
team: this.team.summary(playerId),
|
||||
expeditions: this.expeditions.summary(playerId),
|
||||
cardProgress: this.expeditions.cardProgressView(playerId),
|
||||
equipment: this.expeditions.equipmentChoices(playerId),
|
||||
|
|
@ -758,6 +765,7 @@ export class CardsService {
|
|||
shopSetting: this.shopSetting,
|
||||
daily: this.dailyAdminSummary(),
|
||||
expeditionSettings: this.expeditions.adminSettings(),
|
||||
teamSettings: this.team.adminSettings(),
|
||||
expeditionsToday: this.expeditions.adminSummary(),
|
||||
packActivity7d,
|
||||
campaigns: this.campaignSummaries(),
|
||||
|
|
@ -902,7 +910,7 @@ export class CardsService {
|
|||
}
|
||||
|
||||
dailyAttemptRow(playerId, day) {
|
||||
return this.db.prepare("SELECT card_id, focus_x, focus_y, guesses_json, hints_json, owned, status, reward FROM daily_attempts WHERE player_id = ? AND day = ?").get(playerId, day);
|
||||
return this.db.prepare("SELECT card_id, focus_x, focus_y, guesses_json, hints_json, owned, status, reward, reward_offer_json, reward_choice FROM daily_attempts WHERE player_id = ? AND day = ?").get(playerId, day);
|
||||
}
|
||||
|
||||
// Partie du joueur pour ce jour, tirée s'il n'en a pas encore : pas de carte qu'il a déjà eue ces 60 derniers jours.
|
||||
|
|
@ -918,7 +926,7 @@ export class CardsService {
|
|||
const row = this.dailyAttemptRow(playerId, day);
|
||||
// Une carte retirée du catalogue après son tirage ne peut plus être affichée.
|
||||
if (!this.index.cards.has(row.card_id)) fail(503, "DAILY_UNAVAILABLE", "La Carte du jour est indisponible.");
|
||||
return { day, number, cardId: row.card_id, focus: { x: row.focus_x, y: row.focus_y }, guesses: JSON.parse(row.guesses_json), hints: JSON.parse(row.hints_json), status: row.status, earned: row.reward,
|
||||
return { day, number, cardId: row.card_id, focus: { x: row.focus_x, y: row.focus_y }, guesses: JSON.parse(row.guesses_json), hints: JSON.parse(row.hints_json), status: row.status, earned: row.reward, rewardChoice: row.reward_choice, rewardOffer: row.reward_offer_json ? JSON.parse(row.reward_offer_json) : null,
|
||||
// Une partie tirée avant que la possession soit figée la lit dans la collection.
|
||||
owned: row.owned == null ? this.ownsCard(playerId, row.card_id) : Boolean(row.owned) };
|
||||
}
|
||||
|
|
@ -1006,6 +1014,9 @@ export class CardsService {
|
|||
collectionIds: this.dailyCollectionIds(playerId, puzzle.cardId),
|
||||
reward: this.shopSetting.dailyReward,
|
||||
earned: puzzle.earned,
|
||||
// Récompense à choisir après une victoire : les deux montants de poussière, le second avec une étoile dorée.
|
||||
rewardOffer: puzzle.rewardChoice === "pending" ? { ...puzzle.rewardOffer, starAvailable: this.canEarnStar(playerId), goldStars: this.team.goldStars(playerId), maxGoldStars: MAX_GOLD_RESERVE } : null,
|
||||
earnedStar: puzzle.rewardChoice === "star",
|
||||
streak: this.dailyStreak(playerId, puzzle.day),
|
||||
nextAt: nextDailyAt(this.now()),
|
||||
answerCardId: finished ? puzzle.cardId : null,
|
||||
|
|
@ -1025,7 +1036,7 @@ export class CardsService {
|
|||
const number = this.database.transaction(() => this.ensureDailyDay(day));
|
||||
const row = this.dailyAttemptRow(playerId, day);
|
||||
const guesses = row ? JSON.parse(row.guesses_json) : [];
|
||||
return { day, number, status: row?.status || "playing", guessCount: guesses.length, maxGuesses: MAX_DAILY_GUESSES, streak: this.dailyStreak(playerId, day) };
|
||||
return { day, number, status: row?.status || "playing", rewardPending: row?.reward_choice === "pending", guessCount: guesses.length, maxGuesses: MAX_DAILY_GUESSES, streak: this.dailyStreak(playerId, day) };
|
||||
}
|
||||
|
||||
// Un essai vaut pour le jour annoncé par le client : après minuit, il doit recharger la nouvelle partie.
|
||||
|
|
@ -1042,19 +1053,61 @@ export class CardsService {
|
|||
const guesses = [...puzzle.guesses, cardId];
|
||||
const won = cardId === puzzle.cardId;
|
||||
const status = won ? "won" : guesses.length >= MAX_DAILY_GUESSES ? "lost" : "playing";
|
||||
const reward = won ? this.shopSetting.dailyReward : 0;
|
||||
this.db.prepare("UPDATE daily_attempts SET guesses_json = ?, status = ?, reward = ?, updated_at = ? WHERE player_id = ? AND day = ?")
|
||||
.run(JSON.stringify(guesses), status, reward, this.now(), playerId, today);
|
||||
// Tant que l'Équipe du jour est ouverte et la réserve d'étoiles pas pleine, la récompense attend le choix du joueur.
|
||||
const rewardOffer = won && this.canEarnStar(playerId) ? { stardust: this.shopSetting.dailyReward, starStardust: this.team.settings.starStardust } : null;
|
||||
const rewardChoice = rewardOffer ? "pending" : null;
|
||||
const reward = won && !rewardOffer ? this.shopSetting.dailyReward : 0;
|
||||
this.db.prepare("UPDATE daily_attempts SET guesses_json = ?, status = ?, reward = ?, reward_offer_json = ?, reward_choice = ?, updated_at = ? WHERE player_id = ? AND day = ?")
|
||||
.run(JSON.stringify(guesses), status, reward, rewardOffer && JSON.stringify(rewardOffer), rewardChoice, this.now(), playerId, today);
|
||||
if (won) {
|
||||
if (reward) this.db.prepare("UPDATE players SET stardust = stardust + ? WHERE id = ?").run(reward, playerId);
|
||||
this.audit(playerId, "daily_won", today, { number: puzzle.number, cardId, guesses: guesses.length, stardust: reward });
|
||||
}
|
||||
return this.dailyView(playerId, { ...puzzle, guesses, status, earned: reward });
|
||||
return this.dailyView(playerId, { ...puzzle, guesses, status, earned: reward, rewardOffer, rewardChoice });
|
||||
});
|
||||
// L'état complet suit chaque essai : résumé de la quête du jour et, après une victoire, solde et historique.
|
||||
return { daily, state: this.getState(playerId) };
|
||||
}
|
||||
|
||||
canEarnStar(playerId) {
|
||||
return this.team.settings.enabled && this.team.goldStars(playerId) < MAX_GOLD_RESERVE;
|
||||
}
|
||||
|
||||
// Récompense d'une victoire : de la poussière, ou moins de poussière et une étoile dorée pour le prochain recrutement.
|
||||
chooseDailyReward(playerId, { day, choice } = {}) {
|
||||
if (!isDayKey(day) || !["stardust", "star"].includes(choice)) fail(400, "DAILY_REWARD_INVALID", "Récompense invalide.");
|
||||
const daily = this.database.transaction(() => {
|
||||
const today = dailyDayKey(this.now());
|
||||
this.settleDailyRewards(playerId);
|
||||
if (day !== today) fail(409, "DAILY_EXPIRED", "Une nouvelle Carte du jour est arrivée : rechargez la partie.");
|
||||
const puzzle = this.ensureDailyPuzzle(playerId, today);
|
||||
if (puzzle.rewardChoice !== "pending") {
|
||||
// Le même choix envoyé deux fois (double clic, deux onglets) ne change rien.
|
||||
if (puzzle.rewardChoice === choice) return this.dailyView(playerId, puzzle);
|
||||
fail(409, "DAILY_REWARD_CHOSEN", "Cette récompense est déjà choisie.");
|
||||
}
|
||||
if (choice === "star" && !this.canEarnStar(playerId)) fail(409, "DAILY_STAR_UNAVAILABLE", "Vous ne pouvez pas recevoir d’étoile dorée pour le moment.");
|
||||
this.payDailyReward(playerId, today, puzzle.rewardOffer, choice);
|
||||
return this.dailyView(playerId, this.ensureDailyPuzzle(playerId, today));
|
||||
});
|
||||
return { daily, state: this.getState(playerId) };
|
||||
}
|
||||
|
||||
payDailyReward(playerId, day, offer, choice) {
|
||||
const stardust = choice === "star" ? offer.starStardust : offer.stardust;
|
||||
this.db.prepare("UPDATE daily_attempts SET reward = ?, reward_choice = ?, updated_at = ? WHERE player_id = ? AND day = ? AND reward_choice = 'pending'").run(stardust, choice, this.now(), playerId, day);
|
||||
this.db.prepare("UPDATE players SET stardust = stardust + ?, gold_stars = gold_stars + ? WHERE id = ?").run(stardust, choice === "star" ? 1 : 0, playerId);
|
||||
this.audit(playerId, "daily_reward_chosen", day, { stardust, star: choice === "star" });
|
||||
}
|
||||
|
||||
// Une récompense non choisie devient de la poussière au changement de jour. À appeler dans une transaction.
|
||||
settleDailyRewards(playerId) {
|
||||
const today = dailyDayKey(this.now());
|
||||
for (const row of this.db.prepare("SELECT day, reward_offer_json FROM daily_attempts WHERE player_id = ? AND reward_choice = 'pending' AND day < ?").all(playerId, today)) {
|
||||
this.payDailyReward(playerId, row.day, JSON.parse(row.reward_offer_json), "stardust");
|
||||
}
|
||||
}
|
||||
|
||||
// Un indice par essai raté, au choix ; il ne coûte aucun essai et vaut pour le jour annoncé par le client.
|
||||
useDailyHint(playerId, { day, hint } = {}) {
|
||||
if (!isDayKey(day) || !DAILY_HINTS.includes(hint)) fail(400, "DAILY_HINT_INVALID", "Indice invalide.");
|
||||
|
|
@ -1167,6 +1220,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);
|
||||
this.team.forgetPlayer(playerId);
|
||||
this.expeditions.forgetAlertsInTx(playerId);
|
||||
this.expeditions.forgetItemsInTx(playerId);
|
||||
for (const table of ["sessions", "collection_cards", "favorites", "idempotency", "daily_attempts", "card_progress", "card_equipment"]) this.db.prepare(`DELETE FROM ${table} WHERE player_id = ?`).run(playerId);
|
||||
|
|
|
|||
140
services/cards/team-race.js
Normal file
140
services/cards/team-race.js
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
// Rôle : Course des courants avec la base (adversaires, départ, élans, arrivée, récompense). Méthodes ajoutées à TeamService.
|
||||
import { dailyDayKey, isDayKey, shiftDayKey } from "./daily.js";
|
||||
import { autoRun, bestRunner, boostsError, MAX_RACE_MS, placeOf, RACERS, replayRun } from "./race-rules.js";
|
||||
import { companionStats, inventTeam, shuffle, TEAM_DAYS, teamCharacters, WATCHER_TEAM_LEVELS } from "./team-rules.js";
|
||||
|
||||
// Délai laissé après la plus longue course possible : au-delà, une course quittée se termine avec les élans déjà donnés.
|
||||
const ABANDON_MS = MAX_RACE_MS + 60_000;
|
||||
|
||||
function fail(status, code, message) {
|
||||
throw Object.assign(new Error(message), { status, code });
|
||||
}
|
||||
|
||||
// Coureur et équipiers d'une équipe : cartes et stats figées au départ.
|
||||
function entrantOf(companions, runnerIndex) {
|
||||
const racer = ({ cardId, profile, power }) => ({ cardId, stats: companionStats(profile, power) });
|
||||
return { runner: racer(companions[runnerIndex]), helpers: companions.filter((_, index) => index !== runnerIndex).map(racer) };
|
||||
}
|
||||
|
||||
const statsOf = ({ runner, helpers }) => ({ runner: runner.stats, helpers: helpers.map((helper) => helper.stats) });
|
||||
|
||||
export const raceMethods = {
|
||||
raceRow(playerId, day) {
|
||||
const row = this.db.prepare("SELECT day, status, started_at, race_json, boosts_json, place, reward FROM team_races WHERE player_id = ? AND day = ?").get(playerId, day);
|
||||
return row ? { day: row.day, status: row.status, startedAt: row.started_at, race: JSON.parse(row.race_json), boosts: JSON.parse(row.boosts_json), place: row.place, reward: row.reward } : null;
|
||||
},
|
||||
|
||||
// Course en cours du joueur, même commencée avant minuit.
|
||||
runningRace(playerId) {
|
||||
const row = this.db.prepare("SELECT day FROM team_races WHERE player_id = ? AND status = 'running' ORDER BY day DESC LIMIT 1").get(playerId);
|
||||
return row ? this.raceRow(playerId, row.day) : null;
|
||||
},
|
||||
|
||||
// Trois adversaires : les équipes utilisables d'autres joueurs, tirées au hasard et jouées automatiquement, complétées par des
|
||||
// Équipes des Veilleurs de niveaux différents. Le pseudo n'est pas copié : il se lit à l'affichage (compte renommé ou supprimé).
|
||||
drawOpponents(playerId, day, zones) {
|
||||
const rows = this.db.prepare(`SELECT t.player_id, t.state_json FROM player_teams t JOIN players p ON p.id = t.player_id
|
||||
WHERE t.player_id != ? AND t.ready_day BETWEEN ? AND ? AND p.deleted_at IS NULL ORDER BY t.player_id`).all(playerId, shiftDayKey(day, 1 - TEAM_DAYS), day);
|
||||
const opponents = shuffle(rows, this.random).slice(0, RACERS - 1).map((row) => ({ playerId: row.player_id, companions: JSON.parse(row.state_json).team, skilled: this.random(2) === 0 }));
|
||||
const characters = teamCharacters(this.cards.catalog);
|
||||
const levels = shuffle(Object.entries(WATCHER_TEAM_LEVELS), this.random);
|
||||
while (opponents.length < RACERS - 1) {
|
||||
const [level, skill] = levels.pop();
|
||||
opponents.push({ playerId: null, companions: inventTeam(characters, zones, skill, this.random, this.settings.recruitment), skilled: level === "strong" });
|
||||
}
|
||||
return shuffle(opponents, this.random).map(({ playerId: opponentId, companions, skilled }) => {
|
||||
const entrant = entrantOf(companions, bestRunner(companions.map(({ profile, power }) => companionStats(profile, power)), zones));
|
||||
const run = autoRun(statsOf(entrant), zones, skilled, this.random);
|
||||
return { playerId: opponentId, ...entrant, boosts: run.boosts, finishedAt: run.finishedAt };
|
||||
});
|
||||
},
|
||||
|
||||
startRace(playerId, { day, cardId } = {}) {
|
||||
if (!isDayKey(day) || typeof cardId !== "string") fail(400, "RACE_INVALID", "Demande invalide.");
|
||||
this.requireOpen();
|
||||
this.cards.database.transaction(() => {
|
||||
const today = this.today;
|
||||
if (day !== today) fail(409, "TEAM_EXPIRED", "Un nouveau jour a commencé : rechargez la page.");
|
||||
this.settleAbandonedRace(playerId);
|
||||
if (this.raceRow(playerId, today)) fail(409, "RACE_ALREADY_RUN", "Vous avez déjà couru aujourd’hui.");
|
||||
if (this.runningRace(playerId)) fail(409, "RACE_RUNNING", "Une course est déjà en cours.");
|
||||
const team = this.activeTeam(playerId, today);
|
||||
if (!team) fail(409, "RACE_NO_TEAM", "Recrutez d’abord une équipe.");
|
||||
const runnerIndex = team.companions.findIndex((companion) => companion.cardId === cardId);
|
||||
if (runnerIndex < 0) fail(409, "RACE_RUNNER_INVALID", "Ce compagnon n’est pas dans votre équipe.");
|
||||
const zones = this.ensureZones(today);
|
||||
const race = { zones, entrant: entrantOf(team.companions, runnerIndex), opponents: this.drawOpponents(playerId, today, zones), rewards: this.settings.raceRewards };
|
||||
this.db.prepare("INSERT INTO team_races(player_id, day, status, started_at, race_json, boosts_json, place, reward) VALUES (?, ?, 'running', ?, ?, '[]', NULL, 0)").run(playerId, today, this.cards.now(), JSON.stringify(race));
|
||||
});
|
||||
return this.result(playerId);
|
||||
},
|
||||
|
||||
// Élans donnés jusqu'ici. La liste ne peut que s'allonger : recharger la page ne permet pas de recommencer autrement.
|
||||
recordBoosts(playerId, { boosts } = {}) {
|
||||
this.cards.database.transaction(() => {
|
||||
const running = this.runningRace(playerId);
|
||||
if (!running) fail(409, "RACE_NOT_RUNNING", "Aucune course n’est en cours.");
|
||||
this.saveBoosts(playerId, running, boosts);
|
||||
});
|
||||
return { ok: true };
|
||||
},
|
||||
|
||||
saveBoosts(playerId, running, boosts) {
|
||||
const error = boostsError(boosts, running.race.entrant.helpers.length);
|
||||
if (error) fail(400, "RACE_BOOSTS_INVALID", error);
|
||||
const prefix = running.boosts.every((boost, index) => boosts[index]?.at === boost.at && boosts[index]?.helper === boost.helper);
|
||||
// Un envoi en retard, déjà contenu dans ce qui est enregistré, est sans effet.
|
||||
if (!prefix) {
|
||||
const late = boosts.every((boost, index) => running.boosts[index]?.at === boost.at && running.boosts[index]?.helper === boost.helper);
|
||||
if (!late) fail(409, "RACE_BOOSTS_CHANGED", "Les élans déjà donnés ne changent plus.");
|
||||
return running.boosts;
|
||||
}
|
||||
const clean = boosts.map(({ at, helper }) => ({ at, helper }));
|
||||
this.db.prepare("UPDATE team_races SET boosts_json = ? WHERE player_id = ? AND day = ?").run(JSON.stringify(clean), playerId, running.day);
|
||||
return clean;
|
||||
},
|
||||
|
||||
// Le serveur rejoue la course : c'est lui qui donne l'arrivée, la place et la récompense.
|
||||
finishRace(playerId, { boosts } = {}) {
|
||||
this.cards.database.transaction(() => {
|
||||
const running = this.runningRace(playerId);
|
||||
// Une arrivée envoyée deux fois renvoie simplement le résultat.
|
||||
if (!running) {
|
||||
if (this.raceRow(playerId, this.today)) return;
|
||||
fail(409, "RACE_NOT_RUNNING", "Aucune course n’est en cours.");
|
||||
}
|
||||
this.completeRace(playerId, running, boosts == null ? running.boosts : this.saveBoosts(playerId, running, boosts));
|
||||
});
|
||||
return this.result(playerId);
|
||||
},
|
||||
|
||||
completeRace(playerId, { day, race }, boosts) {
|
||||
const run = replayRun({ ...statsOf(race.entrant), boosts }, race.zones);
|
||||
const place = placeOf(run.finishedAt, race.opponents.map((opponent) => opponent.finishedAt));
|
||||
const reward = race.rewards[place - 1] ?? 0;
|
||||
this.db.prepare("UPDATE team_races SET status = 'finished', place = ?, reward = ? WHERE player_id = ? AND day = ? AND status = 'running'").run(place, reward, playerId, day);
|
||||
if (reward) this.db.prepare("UPDATE players SET stardust = stardust + ? WHERE id = ?").run(reward, playerId);
|
||||
this.cards.audit(playerId, "race_finished", day, { place, stardust: reward, cardId: race.entrant.runner.cardId });
|
||||
},
|
||||
|
||||
// À appeler dans une transaction.
|
||||
settleAbandonedRace(playerId) {
|
||||
const running = this.runningRace(playerId);
|
||||
if (running && this.cards.now() - running.startedAt > ABANDON_MS) this.completeRace(playerId, running, running.boosts);
|
||||
},
|
||||
|
||||
raceView(playerId) {
|
||||
const row = this.runningRace(playerId) || this.raceRow(playerId, dailyDayKey(this.cards.now()));
|
||||
if (!row) return null;
|
||||
const names = this.db.prepare("SELECT display_name, avatar_url, deleted_at FROM players WHERE id = ?");
|
||||
const { entrant, opponents, zones, rewards } = row.race;
|
||||
return {
|
||||
day: row.day, status: row.status, zones, rewards, place: row.place, reward: row.reward, boosts: row.boosts, runner: entrant.runner, helpers: entrant.helpers,
|
||||
finishedAt: row.status === "finished" ? replayRun({ ...statsOf(entrant), boosts: row.boosts }, zones).finishedAt : null,
|
||||
opponents: opponents.map((opponent) => {
|
||||
const player = opponent.playerId ? names.get(opponent.playerId) : null;
|
||||
return { name: player && !player.deleted_at ? player.display_name : null, watchers: !opponent.playerId, runner: opponent.runner, helpers: opponent.helpers, boosts: opponent.boosts, finishedAt: opponent.finishedAt };
|
||||
})
|
||||
};
|
||||
}
|
||||
};
|
||||
227
services/cards/team-rules.js
Normal file
227
services/cards/team-rules.js
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
// Rôle : règles pures de l'Équipe du jour (spécialités, personnages proposés, étoiles, recrutement, durée d'une équipe).
|
||||
// Le service les applique avec la base ; aucune fonction ici ne lit la base ni l'horloge. Règles : 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,
|
||||
// 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);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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.";
|
||||
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é, 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 highest - Math.min(...values) <= BALANCED_SPREAD ? [] : [best[0]];
|
||||
}
|
||||
|
||||
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) }];
|
||||
});
|
||||
}
|
||||
|
||||
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, complétés au besoin par 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 }, random = defaultRandom) {
|
||||
const offer = [];
|
||||
const used = new Set();
|
||||
const take = (candidates) => {
|
||||
const byProfile = new Map();
|
||||
for (const character of candidates) {
|
||||
const key = profileKey(character.profile);
|
||||
if (seenIds.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)]);
|
||||
}
|
||||
};
|
||||
take(characters.filter((character) => poolIds.has(character.id)));
|
||||
if (offer.length < OFFER_SIZE) take(characters.filter((character) => character.active && !poolIds.has(character.id)));
|
||||
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 };
|
||||
return nextOffer(characters, ownedIds, state, random);
|
||||
}
|
||||
|
||||
function nextOffer(characters, ownedIds, state, random) {
|
||||
const poolIds = new Set([...ownedIds, ...state.lentIds]);
|
||||
const offer = drawOffer(characters, { poolIds, seenIds: new Set(state.seenIds) }, 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;
|
||||
}
|
||||
|
||||
export const recruitmentFinished = (state) => state.team.length >= TEAM_SIZE;
|
||||
|
||||
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 } };
|
||||
}
|
||||
|
||||
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] } } };
|
||||
}
|
||||
|
||||
// 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 } = state.current;
|
||||
const next = { ...state, team: [...state.team, { cardId, profile, power, step, fallen, lent: !ownedIds.has(cardId) }], current: null, offer: [] };
|
||||
return recruitmentFinished(next) ? next : 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.
|
||||
export function inventTeam(characters, zones, skill, random = defaultRandom, settings = DEFAULT_TEAM_SETTINGS) {
|
||||
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, 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;
|
||||
}
|
||||
227
services/cards/team-service.js
Normal file
227
services/cards/team-service.js
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
// Rôle : applique les règles de l'Équipe du jour avec la base (parcours du jour, recrutement, étoiles en réserve, réglages).
|
||||
// Branché sur CardsService (`service.team`) : il réutilise sa base, son horloge, son hasard, son audit et sa collection.
|
||||
import { dailyDayKey, isDayKey, nextDailyAt } from "./daily.js";
|
||||
import { drawZones } from "./race-rules.js";
|
||||
import {
|
||||
canRevealStar, chooseCharacter, companionStats, hiddenStars, keepCompanion, MAX_GOLD_RESERVE, recruitmentFinished, repairRecruitment, revealStar, specialtiesOf,
|
||||
startRecruitment, TEAM_DAYS, TEAM_SIZE, teamCharacters, teamDay, visibleSky
|
||||
} from "./team-rules.js";
|
||||
import { raceMethods } from "./team-race.js";
|
||||
import { dailyTeamSettingsError, DEFAULT_DAILY_TEAM_SETTINGS, normalizeDailyTeamSettings, readDailyTeamSettings } from "./team-settings.js";
|
||||
|
||||
function fail(status, code, message) {
|
||||
throw Object.assign(new Error(message), { status, code });
|
||||
}
|
||||
|
||||
export class TeamService {
|
||||
constructor(cards) {
|
||||
this.cards = cards;
|
||||
this.db = cards.db;
|
||||
this.random = (max) => cards.random(max);
|
||||
}
|
||||
|
||||
get today() {
|
||||
return dailyDayKey(this.cards.now());
|
||||
}
|
||||
|
||||
// --- Réglages -----------------------------------------------------------------------------------------------------------
|
||||
|
||||
get settings() {
|
||||
const row = this.db.prepare("SELECT settings_json FROM team_settings WHERE id = 1").get();
|
||||
return readDailyTeamSettings(JSON.parse(row?.settings_json || "{}"), (error) => console.error(`Invalid stored team settings, using defaults: ${error}`));
|
||||
}
|
||||
|
||||
adminSettings() {
|
||||
return { settings: this.settings, defaults: normalizeDailyTeamSettings(DEFAULT_DAILY_TEAM_SETTINGS), updatedAt: this.db.prepare("SELECT updated_at FROM team_settings WHERE id = 1").get()?.updated_at ?? 0 };
|
||||
}
|
||||
|
||||
// Un recrutement commencé garde les réglages de son début (voir startRecruitment).
|
||||
updateSettings(adminId, settings) {
|
||||
this.cards.requireAdmin(adminId);
|
||||
const error = dailyTeamSettingsError(settings);
|
||||
if (error) fail(400, "TEAM_SETTINGS_INVALID", error);
|
||||
const previous = this.settings;
|
||||
const next = normalizeDailyTeamSettings(settings);
|
||||
if (JSON.stringify(previous) === JSON.stringify(next)) fail(409, "TEAM_SETTINGS_UNCHANGED", "Ces réglages sont déjà en vigueur.");
|
||||
this.cards.database.transaction(() => {
|
||||
this.db.prepare("UPDATE team_settings SET settings_json = ?, updated_at = ?, updated_by = ? WHERE id = 1").run(JSON.stringify(next), this.cards.now(), adminId);
|
||||
this.cards.audit(adminId, "team_settings_updated", "team", { previous, next });
|
||||
});
|
||||
return { teamSettings: this.adminSettings() };
|
||||
}
|
||||
|
||||
requireOpen() {
|
||||
if (!this.settings.enabled) fail(409, "TEAM_CLOSED", "L’Équipe du jour est fermée pour le moment.");
|
||||
}
|
||||
|
||||
// --- Lectures -----------------------------------------------------------------------------------------------------------
|
||||
|
||||
// Parcours de la Course, commun à tous les joueurs d'un jour. À appeler dans une transaction.
|
||||
ensureZones(day) {
|
||||
const read = () => this.db.prepare("SELECT zones_json FROM team_days WHERE day = ?").get(day);
|
||||
if (!read()) this.db.prepare("INSERT INTO team_days(day, zones_json, created_at) VALUES (?, ?, ?)").run(day, JSON.stringify(drawZones(this.random)), this.cards.now());
|
||||
return JSON.parse(read().zones_json);
|
||||
}
|
||||
|
||||
goldStars(playerId) {
|
||||
return this.db.prepare("SELECT gold_stars FROM players WHERE id = ?").get(playerId)?.gold_stars ?? 0;
|
||||
}
|
||||
|
||||
teamRow(playerId) {
|
||||
const row = this.db.prepare("SELECT started_day, ready_day, state_json FROM player_teams WHERE player_id = ?").get(playerId);
|
||||
return row ? { startedDay: row.started_day, readyDay: row.ready_day, state: JSON.parse(row.state_json) } : null;
|
||||
}
|
||||
|
||||
// L'équipe du joueur, son recrutement en cours réparé s'il cite une carte retirée du catalogue. À appeler dans une transaction.
|
||||
repairedRow(playerId, { characters, owned }) {
|
||||
const row = this.teamRow(playerId);
|
||||
if (!row || row.readyDay) return row;
|
||||
const state = repairRecruitment(characters, owned, row.state, this.random);
|
||||
if (state !== row.state) this.saveState(playerId, state, null);
|
||||
return { ...row, state };
|
||||
}
|
||||
|
||||
saveState(playerId, state, readyDay) {
|
||||
this.db.prepare("UPDATE player_teams SET ready_day = ?, state_json = ?, updated_at = ? WHERE player_id = ?").run(readyDay, JSON.stringify(state), this.cards.now(), playerId);
|
||||
}
|
||||
|
||||
// Cartes que le joueur voit dans son album : celles d'un paquet pas encore révélé ne comptent pas.
|
||||
ownedCardIds(playerId) {
|
||||
const pending = this.db.prepare("SELECT id FROM openings WHERE player_id = ? AND status = 'pending' ORDER BY created_at DESC LIMIT 1").get(playerId);
|
||||
return new Set(this.cards.visibleCollection(playerId, pending?.id).map((entry) => this.cards.index.editions.get(entry.editionId)?.cardId).filter(Boolean));
|
||||
}
|
||||
|
||||
// Équipe utilisable aujourd'hui : recrutement terminé et pas plus de TEAM_DAYS jours. `day` : son rang, de 1 à TEAM_DAYS.
|
||||
activeTeam(playerId, day = this.today) {
|
||||
const row = this.teamRow(playerId);
|
||||
const rank = row?.readyDay ? teamDay(row.readyDay, day) : 0;
|
||||
return rank ? { day: rank, companions: row.state.team } : null;
|
||||
}
|
||||
|
||||
companionView({ cardId, profile, power, step = 0, fallen = false, lent = false }) {
|
||||
return { cardId, power, step, fallen, lent, stats: companionStats(profile, power), specialties: specialtiesOf(profile) };
|
||||
}
|
||||
|
||||
// Le client ne reçoit ni la place des étoiles cachées, ni les personnages suivants.
|
||||
recruitmentView(state, characters, owned) {
|
||||
const byId = new Map(characters.map((character) => [character.id, character]));
|
||||
const preview = (cardId) => this.companionView({ cardId, profile: byId.get(cardId).profile, power: state.settings.powers[0], lent: !owned.has(cardId) });
|
||||
return {
|
||||
size: TEAM_SIZE, powers: state.settings.powers, fallPower: state.settings.fallPower, dustValue: state.settings.dustValue, extraGold: state.extraGold, dust: state.dust,
|
||||
offer: state.current ? [] : state.offer.map(preview),
|
||||
current: state.current ? this.companionView({ ...state.current, profile: byId.get(state.current.cardId).profile, lent: !owned.has(state.current.cardId) }) : null,
|
||||
sky: visibleSky(state), hidden: hiddenStars(state)
|
||||
};
|
||||
}
|
||||
|
||||
view(playerId) {
|
||||
const day = this.today;
|
||||
const settings = this.settings;
|
||||
const zones = this.cards.database.transaction(() => this.ensureZones(day));
|
||||
const recruitable = { characters: teamCharacters(this.cards.catalog), owned: this.ownedCardIds(playerId) };
|
||||
const row = this.cards.database.transaction(() => {
|
||||
this.settleAbandonedRace(playerId);
|
||||
return this.repairedRow(playerId, recruitable);
|
||||
});
|
||||
const recruiting = Boolean(row && !row.readyDay);
|
||||
const rank = row?.readyDay ? teamDay(row.readyDay, day) : 0;
|
||||
const base = {
|
||||
enabled: settings.enabled, day, nextAt: nextDailyAt(this.cards.now()), zones, goldStars: this.goldStars(playerId), maxGoldStars: MAX_GOLD_RESERVE, maxDays: TEAM_DAYS,
|
||||
// Un recrutement par jour, et jamais deux à la fois.
|
||||
canRecruit: settings.enabled && !recruiting && row?.startedDay !== day,
|
||||
status: recruiting ? "recruiting" : rank ? "ready" : row ? "expired" : "none",
|
||||
teamDay: rank, companions: row ? row.state.team.map((companion) => this.companionView(companion)) : [], recruitment: null,
|
||||
race: this.raceView(playerId)
|
||||
};
|
||||
if (!recruiting) return { ...base, lastSky: row ? visibleSky(row.state) : null, lastDust: row?.state.dust ?? 0 };
|
||||
return { ...base, recruitment: this.recruitmentView(row.state, recruitable.characters, recruitable.owned) };
|
||||
}
|
||||
|
||||
// Résumé pour le tableau de bord et la Guilde, sans rien tirer.
|
||||
summary(playerId) {
|
||||
const row = this.teamRow(playerId);
|
||||
const rank = row?.readyDay ? teamDay(row.readyDay, this.today) : 0;
|
||||
const race = this.runningRace(playerId) || this.raceRow(playerId, this.today);
|
||||
return { enabled: this.settings.enabled, race: race?.status ?? "none", status: row && !row.readyDay ? "recruiting" : rank ? "ready" : row ? "expired" : "none", teamDay: rank, maxDays: TEAM_DAYS, goldStars: this.goldStars(playerId), maxGoldStars: MAX_GOLD_RESERVE };
|
||||
}
|
||||
|
||||
// --- Recrutement --------------------------------------------------------------------------------------------------------
|
||||
|
||||
// Remplace l'équipe du joueur, perdue pour de bon, et dépense toute sa réserve d'étoiles dorées.
|
||||
startRecruitment(playerId, { day } = {}) {
|
||||
if (!isDayKey(day)) fail(400, "TEAM_INVALID", "Demande invalide.");
|
||||
this.requireOpen();
|
||||
this.cards.database.transaction(() => {
|
||||
const today = this.today;
|
||||
if (day !== today) fail(409, "TEAM_EXPIRED", "Un nouveau jour a commencé : rechargez la page.");
|
||||
const row = this.teamRow(playerId);
|
||||
if (row && !row.readyDay) fail(409, "TEAM_RECRUITING", "Un recrutement est déjà en cours.");
|
||||
if (row?.startedDay === today) fail(409, "TEAM_ALREADY_RECRUITED", "Vous avez déjà recruté une équipe aujourd’hui.");
|
||||
const characters = teamCharacters(this.cards.catalog);
|
||||
const state = startRecruitment(characters, { ownedIds: this.ownedCardIds(playerId), goldReserve: this.goldStars(playerId), settings: this.settings.recruitment }, this.random);
|
||||
if (!state.offer.length) fail(409, "TEAM_UNAVAILABLE", "Aucun personnage ne peut être recruté aujourd’hui.");
|
||||
this.db.prepare("UPDATE players SET gold_stars = 0 WHERE id = ?").run(playerId);
|
||||
const now = this.cards.now();
|
||||
this.db.prepare(`INSERT INTO player_teams(player_id, started_day, ready_day, state_json, created_at, updated_at) VALUES (?, ?, NULL, ?, ?, ?)
|
||||
ON CONFLICT(player_id) DO UPDATE SET started_day = excluded.started_day, ready_day = NULL, state_json = excluded.state_json, created_at = excluded.created_at, updated_at = excluded.updated_at`)
|
||||
.run(playerId, today, JSON.stringify(state), now, now);
|
||||
});
|
||||
return this.result(playerId);
|
||||
}
|
||||
|
||||
chooseCharacter(playerId, { cardId } = {}) {
|
||||
return this.change(playerId, (state) => {
|
||||
// Choisir deux fois le même personnage (double clic, deux onglets) ne change rien.
|
||||
if (state.current?.cardId === cardId) return state;
|
||||
return chooseCharacter(state, cardId) ?? fail(409, "TEAM_CHOICE_INVALID", "Ce personnage ne peut plus être recruté.");
|
||||
});
|
||||
}
|
||||
|
||||
revealStar(playerId, { index } = {}) {
|
||||
return this.change(playerId, (state) => {
|
||||
if (state.current && state.revealed.includes(index)) return state;
|
||||
if (!canRevealStar(state, index)) fail(409, "TEAM_STAR_INVALID", "Cette étoile ne peut pas être révélée.");
|
||||
const result = revealStar(state, index);
|
||||
if (result.star === "dust" && state.settings.dustValue) this.db.prepare("UPDATE players SET stardust = stardust + ? WHERE id = ?").run(state.settings.dustValue, playerId);
|
||||
return result.state;
|
||||
});
|
||||
}
|
||||
|
||||
// `cardId` : le compagnon que le client croit garder, pour qu'un double clic ne garde pas le suivant.
|
||||
keepCompanion(playerId, { cardId } = {}) {
|
||||
return this.change(playerId, (state, characters, owned) => {
|
||||
if (state.current?.cardId !== cardId) fail(409, "TEAM_CHOICE_INVALID", "Ce compagnon n’est plus en cours de recrutement.");
|
||||
return keepCompanion(characters, owned, state, this.random);
|
||||
});
|
||||
}
|
||||
|
||||
change(playerId, apply) {
|
||||
this.cards.database.transaction(() => {
|
||||
const characters = teamCharacters(this.cards.catalog);
|
||||
const owned = this.ownedCardIds(playerId);
|
||||
const row = this.repairedRow(playerId, { characters, owned });
|
||||
if (!row || row.readyDay) fail(409, "TEAM_NOT_RECRUITING", "Aucun recrutement n’est en cours.");
|
||||
const next = apply(row.state, characters, owned);
|
||||
if (next === row.state) return;
|
||||
const finished = recruitmentFinished(next);
|
||||
// L'équipe sert à partir du jour où elle est complète.
|
||||
this.saveState(playerId, next, finished ? this.today : null);
|
||||
if (finished) {
|
||||
this.cards.audit(playerId, "team_recruited", this.today, { cards: next.team.map((companion) => companion.cardId), power: Math.round(next.team.reduce((sum, companion) => sum + companion.power, 0) / next.team.length), stardust: next.dust, goldStars: next.extraGold });
|
||||
}
|
||||
});
|
||||
return this.result(playerId);
|
||||
}
|
||||
|
||||
result(playerId) {
|
||||
return { team: this.view(playerId), state: this.cards.getState(playerId) };
|
||||
}
|
||||
|
||||
// Suppression de compte : l'équipe disparaît, la réserve est remise à zéro avec le reste des possessions.
|
||||
forgetPlayer(playerId) {
|
||||
for (const table of ["player_teams", "team_races"]) this.db.prepare(`DELETE FROM ${table} WHERE player_id = ?`).run(playerId);
|
||||
this.db.prepare("UPDATE players SET gold_stars = 0 WHERE id = ?").run(playerId);
|
||||
}
|
||||
}
|
||||
|
||||
Object.assign(TeamService.prototype, raceMethods);
|
||||
33
services/cards/team-settings.js
Normal file
33
services/cards/team-settings.js
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
// Rôle : réglages de l'Équipe du jour (ouverture, étoiles, récompenses) : valeurs par défaut, validation et lecture tolérante.
|
||||
import { RACE_REWARDS, RACERS } from "./race-rules.js";
|
||||
import { DEFAULT_TEAM_SETTINGS, teamSettingsError } from "./team-rules.js";
|
||||
|
||||
const MAX_REWARD = 100_000;
|
||||
|
||||
// `starStardust` : poussière reçue avec une étoile dorée quand le joueur choisit cette récompense pour la Carte du jour.
|
||||
export const DEFAULT_DAILY_TEAM_SETTINGS = Object.freeze({
|
||||
enabled: false, starStardust: 10, raceRewards: RACE_REWARDS, recruitment: DEFAULT_TEAM_SETTINGS
|
||||
});
|
||||
|
||||
export function dailyTeamSettingsError(settings) {
|
||||
const reward = (value) => Number.isInteger(value) && value >= 0 && value <= MAX_REWARD;
|
||||
if (!settings || typeof settings !== "object" || Array.isArray(settings)) return "Réglages de l’Équipe du jour invalides.";
|
||||
if (typeof settings.enabled !== "boolean") return "L’ouverture de l’Équipe du jour doit être vraie ou fausse.";
|
||||
if (!reward(settings.starStardust)) return `Poussière reçue avec une étoile : un entier entre 0 et ${MAX_REWARD.toLocaleString("fr-FR")}.`;
|
||||
if (!Array.isArray(settings.raceRewards) || settings.raceRewards.length !== RACERS || !settings.raceRewards.every(reward)) return `Récompenses de la Course : ${RACERS} entiers entre 0 et ${MAX_REWARD.toLocaleString("fr-FR")}.`;
|
||||
return teamSettingsError(settings.recruitment);
|
||||
}
|
||||
|
||||
const pickRecruitment = ({ goldStars, blackStars, dustStars, dustValue, powers, fallPower }) => ({ goldStars, blackStars, dustStars, dustValue, powers: [...powers], fallPower });
|
||||
|
||||
// Garde seulement les champs connus.
|
||||
export const normalizeDailyTeamSettings = ({ enabled, starStardust, raceRewards, recruitment }) => ({ enabled, starStardust, raceRewards: [...raceRewards], recruitment: pickRecruitment(recruitment) });
|
||||
|
||||
// Réglages enregistrés : des valeurs invalides laissent la place aux valeurs par défaut, pour que le jeu reste jouable.
|
||||
export function readDailyTeamSettings(stored, onInvalid = () => {}) {
|
||||
const merged = { ...DEFAULT_DAILY_TEAM_SETTINGS, ...stored, recruitment: { ...DEFAULT_TEAM_SETTINGS, ...stored?.recruitment } };
|
||||
const error = dailyTeamSettingsError(merged);
|
||||
if (!error) return normalizeDailyTeamSettings(merged);
|
||||
onInvalid(error);
|
||||
return normalizeDailyTeamSettings({ ...DEFAULT_DAILY_TEAM_SETTINGS, enabled: stored?.enabled === true });
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue