sokko-g/services/cards/duel-service.js
Shinuwa dcb06e439b
Some checks are pending
Validate and deploy Sokko G / deploy (push) Blocked by required conditions
Validate and deploy Sokko G / validate (push) Has started running
Add the Duel des Constellations mini-game
- Guild quest played with the five companions of the daily team on a
  4x4 sky map: arrows from orientation, attack against defence with no
  hidden roll, combos, nine moves, against a Watcher Guardian or another
  player's ghost team, a few games a day.
- Fortune gives clovers: each card ending in the player's camp adds its
  clovers to the stardust reward (the luck roll was removed).
- Board between both hands, drag and drop or click, capture preview,
  animated duel, auto-started game, side colours, short rules.
- Phone layout with colour-only cards and the duel in the mobile mode.
- Admin settings (opening, games per day, rewards, ghost share),
  migration 35, quest board tile with its illustration, docs and tests
  (rules, service, desktop and phone e2e).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 23:08:25 +01:00

244 lines
14 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @file Duel des Constellations de Sokko TCG côté serveur : parties de l'Équipe du jour du joueur contre l'équipe d'un Gardien des
* Veilleurs ou d'un autre joueur (fantôme), coups joués et réponse de l'ordinateur, gains en poussière d'étoiles et réglages.
*
* Contexte : sous-service créé par CardsService (`service.duel`), qui lui fournit base, horloge, hasard, catalogue, audit et
* l'Équipe du jour (`this.cards.team`). Les règles du jeu sont dans duel-rules.js.
* Points d'entrée : `view(playerId)`, `start`, `play`, `summary`, `adminSettings`, `updateSettings`, `forgetPlayer`.
* Utilisé par : service.js ; api.js par `service.duel`.
* Dépend de : duel-rules.js, duel-settings.js, daily.js (jour de Paris), team-rules.js (stats d'un compagnon, équipes inventées),
* race-rules.js (besoins tirés pour le recrutement d'un Gardien).
* Attention :
* - Le serveur joue les coups : le client envoie la carte, la case et, si plusieurs cartes se défendent, celle à défier ;
* l'ordinateur répond dans la même requête. Le hasard (étoiles éteintes, premier joueur, ordinateur) reste ici.
* - On ne joue qu'avec une équipe utilisable : l'Équipe du jour doit être ouverte et recrutée.
* - Une partie garde ses cartes (stats figées au départ), son adversaire et ses gains de départ : recruter une nouvelle équipe ne
* change pas une partie en cours.
* - Un fantôme joue avec l'équipe utilisable d'un autre joueur ; son nom se lit à l'affichage, comme la Course.
* - `resetForTests` n'est exposée par api.js qu'au serveur de développement (`devPerks`).
* @see docs/duel-constellations.md
*/
import { randomUUID } from "node:crypto";
import { dailyDayKey, dayEndsAt, isDayKey, shiftDayKey } from "./daily.js";
import { aiMove, cloversOf, drawBlockedCells, duelCard, duelReward, DuelMoveError, HAND_SIZE, isFinished, newDuel, outcomeOf, playMove, scoreOf } from "./duel-rules.js";
import { DEFAULT_DUEL_SETTINGS, duelSettingsError, normalizeDuelSettings, readDuelSettings } from "./duel-settings.js";
import { drawZones } from "./race-rules.js";
import { companionStats, inventTeam, TEAM_DAYS, teamCharacters } from "./team-rules.js";
function fail(status, code, message) {
throw Object.assign(new Error(message), { status, code });
}
export class DuelService {
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 duel_settings WHERE id = 1").get();
return readDuelSettings(JSON.parse(row?.settings_json || "{}"), (error) => console.error(`Invalid stored duel settings, using defaults: ${error}`));
}
/** Le jour en cours : parties commencées, gagnées, perdues et nulles, contre un fantôme, et la poussière versée. */
adminSummary(day = this.today) {
const rows = this.db.prepare("SELECT status, COUNT(*) AS count, COALESCE(SUM(reward), 0) AS stardust FROM duel_games WHERE day = ? GROUP BY status").all(day);
const of = (status) => rows.find((row) => row.status === status)?.count ?? 0;
const ghosts = this.db.prepare("SELECT COUNT(*) AS count FROM duel_games WHERE day = ? AND json_extract(opponent_json, '$.kind') = 'ghost'").get(day).count;
return { day, started: rows.reduce((sum, row) => sum + row.count, 0), won: of("won"), lost: of("lost"), draw: of("draw"), ghosts, stardust: rows.reduce((sum, row) => sum + row.stardust, 0) };
}
adminSettings() {
return { today: this.adminSummary(), settings: this.settings, defaults: normalizeDuelSettings(DEFAULT_DUEL_SETTINGS), updatedAt: this.db.prepare("SELECT updated_at FROM duel_settings WHERE id = 1").get()?.updated_at ?? 0 };
}
/** Une partie commencée garde les gains de son début. */
updateSettings(adminId, settings) {
this.cards.requireAdmin(adminId);
const error = duelSettingsError(settings);
if (error) fail(400, "DUEL_SETTINGS_INVALID", error);
const previous = this.settings;
const next = normalizeDuelSettings(settings);
if (JSON.stringify(previous) === JSON.stringify(next)) fail(409, "DUEL_SETTINGS_UNCHANGED", "Ces réglages sont déjà en vigueur.");
this.cards.database.transaction(() => {
this.db.prepare("UPDATE duel_settings SET settings_json = ?, updated_at = ?, updated_by = ? WHERE id = 1").run(JSON.stringify(next), this.cards.now(), adminId);
this.cards.audit(adminId, "duel_settings_updated", "duel", { previous, next });
});
return { duelSettings: this.adminSettings() };
}
// --- Cartes -------------------------------------------------------------------------------------------------------------
/** Cartes de duel d'une équipe : un compagnon par carte, avec les stats de sa Puissance. */
teamCards(companions) {
return companions.map(({ cardId, profile, power }) => duelCard({ cardId, stats: companionStats(profile, power) }));
}
/** Cartes de l'équipe utilisable du joueur aujourd'hui, ou null (Équipe du jour fermée, pas d'équipe, équipe trop vieille). */
playerCards(playerId, day) {
if (!this.cards.team.settings.enabled) return null;
const team = this.cards.team.activeTeam(playerId, day);
return team?.companions.length === HAND_SIZE ? this.teamCards(team.companions) : null;
}
/** Équipe d'un Gardien des Veilleurs, recrutée comme celles de la Course, à un niveau tiré au hasard. */
guardianCards() {
const { watcherSkill, recruitment } = this.cards.team.settings;
const levels = Object.values(watcherSkill);
const skill = levels[this.random(levels.length)];
return this.teamCards(inventTeam(teamCharacters(this.cards.catalog), drawZones(this.random), skill, this.random, recruitment));
}
/** Fantôme possible : l'équipe utilisable d'un autre joueur, tiré au hasard. */
ghostOpponent(playerId, day) {
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)
.filter((row) => JSON.parse(row.state_json).team?.length === HAND_SIZE);
if (!rows.length) return null;
const row = rows[this.random(rows.length)];
return { playerId: row.player_id, hand: this.teamCards(JSON.parse(row.state_json).team) };
}
// --- Lectures -----------------------------------------------------------------------------------------------------------
gameRow(where, ...values) {
const row = this.db.prepare(`SELECT id, player_id, day, status, opponent_json, state_json, reward, rewards_json, started_at, finished_at FROM duel_games WHERE ${where}`).get(...values);
return row ? { id: row.id, playerId: row.player_id, day: row.day, status: row.status, opponent: JSON.parse(row.opponent_json), state: JSON.parse(row.state_json), reward: row.reward, rewards: JSON.parse(row.rewards_json), startedAt: row.started_at, finishedAt: row.finished_at } : null;
}
/** La partie à afficher : celle en cours, sinon la dernière du jour. */
currentGame(playerId, day) {
return this.gameRow("player_id = ? AND status = 'playing' ORDER BY started_at DESC LIMIT 1", playerId)
|| this.gameRow("player_id = ? AND day = ? ORDER BY started_at DESC LIMIT 1", playerId, day);
}
opponentView(opponent) {
if (opponent.kind !== "ghost") return { kind: "guardian", name: null };
const player = this.db.prepare("SELECT display_name, deleted_at FROM players WHERE id = ?").get(opponent.playerId);
return { kind: "ghost", name: player && !player.deleted_at ? player.display_name : null };
}
gameView(game) {
const { state } = game;
const finished = game.status !== "playing";
return {
id: game.id, day: game.day, status: game.status, opponent: this.opponentView(game.opponent),
board: state.board, cards: state.cards, hands: { player: state.hands.player, opponent: state.hands.opponent }, turn: state.turn, starter: state.starter,
moves: state.moves, log: state.log, score: scoreOf(state), rewards: game.rewards,
reward: game.reward, sweep: finished ? outcomeOf(state).sweep : false, clover: cloversOf(state)
};
}
playedOn(playerId, day) {
return this.db.prepare("SELECT COUNT(*) AS count FROM duel_games WHERE player_id = ? AND day = ?").get(playerId, day).count;
}
view(playerId, day = this.today) {
const settings = this.settings;
const game = this.currentGame(playerId, day);
return {
enabled: settings.enabled, day, nextAt: dayEndsAt(day), gamesPerDay: settings.gamesPerDay, played: this.playedOn(playerId, day),
rewards: settings.rewards, handSize: HAND_SIZE,
// L'équipe qui jouera la prochaine partie ; `teamOpen` faux : l'Équipe du jour est fermée, on ne peut pas jouer.
teamOpen: this.cards.team.settings.enabled, team: this.playerCards(playerId, day),
game: game ? this.gameView(game) : null,
devReset: Boolean(this.cards.devPerks)
};
}
/** Résumé pour la Guilde. */
summary(playerId) {
const settings = this.settings;
const day = this.today;
const playing = Boolean(this.db.prepare("SELECT 1 FROM duel_games WHERE player_id = ? AND status = 'playing'").get(playerId));
return { enabled: settings.enabled, played: this.playedOn(playerId, day), gamesPerDay: settings.gamesPerDay, playing, teamReady: Boolean(this.playerCards(playerId, day)) };
}
// --- Parties ------------------------------------------------------------------------------------------------------------
/**
* Commence une partie avec l'Équipe du jour du joueur. L'adversaire est le fantôme d'un autre joueur (`ghostChance` %, s'il en
* existe un) ou un Gardien des Veilleurs. Si l'ordinateur commence, il joue aussitôt.
*/
start(playerId, { day } = {}) {
if (!isDayKey(day)) fail(400, "DUEL_INVALID", "Demande invalide.");
const settings = this.settings;
if (!settings.enabled) fail(409, "DUEL_CLOSED", "Le Duel des Constellations est fermé pour le moment.");
this.cards.database.transaction(() => {
const today = this.today;
if (day !== today) fail(409, "DUEL_EXPIRED", "Un nouveau jour a commencé : rechargez la page.");
// Commencer deux fois (double clic, deux onglets) rend simplement la partie en cours.
if (this.db.prepare("SELECT 1 FROM duel_games WHERE player_id = ? AND status = 'playing'").get(playerId)) return;
if (this.playedOn(playerId, today) >= settings.gamesPerDay) fail(409, "DUEL_DAILY_LIMIT", "Vous avez joué toutes vos parties du jour.");
const cards = this.playerCards(playerId, today);
if (!cards) fail(409, "DUEL_NO_TEAM", "Recrutez d’abord votre Équipe du jour à la taverne.");
const ghost = this.random(100) < settings.ghostChance ? this.ghostOpponent(playerId, today) : null;
const opponent = ghost ? { kind: "ghost", playerId: ghost.playerId } : { kind: "guardian" };
const blocked = drawBlockedCells(this.random);
let state = newDuel({ player: cards, opponent: ghost ? ghost.hand : this.guardianCards(), blocked, starter: this.random(2) ? "opponent" : "player" });
if (state.turn === "opponent") state = playMove(state, aiMove(state, "opponent", this.random)).game;
this.db.prepare(`INSERT INTO duel_games(id, player_id, day, status, opponent_json, state_json, reward, rewards_json, started_at, finished_at)
VALUES (?, ?, ?, 'playing', ?, ?, 0, ?, ?, NULL)`).run(randomUUID(), playerId, today, JSON.stringify(opponent), JSON.stringify(state), JSON.stringify(settings.rewards), this.cards.now());
});
return this.result(playerId);
}
/**
* Pose `slot` en `cell` (et défie `target` si plusieurs cartes se défendent), puis l'ordinateur répond. `moves` : les poses que le
* client a vues ; un envoi en double (double clic, deux onglets) ne joue pas deux fois. Une partie commencée la veille se termine
* normalement.
*/
play(playerId, { gameId, slot, cell, target = null, moves } = {}) {
if (typeof gameId !== "string" || typeof slot !== "string" || !Number.isInteger(cell) || !Number.isInteger(moves) || (target !== null && !Number.isInteger(target))) fail(400, "DUEL_INVALID", "Demande invalide.");
this.cards.database.transaction(() => {
const game = this.gameRow("id = ? AND player_id = ?", gameId, playerId);
if (!game) fail(404, "DUEL_NOT_FOUND", "Partie introuvable.");
if (game.status !== "playing") fail(409, "DUEL_FINISHED", "Cette partie est terminée.");
if (moves !== game.state.moves) return;
let state;
try {
state = playMove(game.state, { side: "player", slot, cell, target }).game;
if (!isFinished(state)) state = playMove(state, aiMove(state, "opponent", this.random)).game;
} catch (error) {
if (error instanceof DuelMoveError) fail(409, error.code, error.message);
throw error;
}
this.save(game, state);
});
return this.result(playerId);
}
save(game, state) {
const finished = isFinished(state);
const outcome = finished ? outcomeOf(state) : null;
const reward = finished ? duelReward(game.rewards, outcome) : 0;
this.db.prepare("UPDATE duel_games SET status = ?, state_json = ?, reward = ?, finished_at = ? WHERE id = ? AND status = 'playing'")
.run(finished ? outcome.status : "playing", JSON.stringify(state), reward, finished ? this.cards.now() : null, game.id);
if (!finished) return;
if (reward) this.db.prepare("UPDATE players SET stardust = stardust + ? WHERE id = ?").run(reward, game.playerId);
this.cards.audit(game.playerId, "duel_finished", game.id, { status: outcome.status, score: outcome.score, sweep: outcome.sweep, clover: outcome.clover, stardust: reward, opponent: game.opponent.kind });
}
result(playerId) {
return { duel: this.view(playerId), state: this.cards.getState(playerId) };
}
/** Serveur Vite local (`devPerks`) : efface les parties du joueur, pour rejouer. */
resetForTests(playerId) {
if (!this.cards.devPerks) fail(404, "NOT_FOUND", "Remise à zéro indisponible.");
this.db.prepare("DELETE FROM duel_games WHERE player_id = ?").run(playerId);
return this.result(playerId);
}
forgetPlayer(playerId) {
this.db.prepare("DELETE FROM duel_games WHERE player_id = ?").run(playerId);
}
}