sokko-g/services/cards/team-race.js
Shinuwa 52b35880f2
All checks were successful
Validate and deploy Sokko G / validate (push) Successful in 23m2s
Validate and deploy Sokko G / deploy (push) Successful in 16s
Rework the daily team screens, share its team block and give the race its admin tab
The daily team page now opens on a welcome screen with the three steps,
and the recruitment keeps the same look: golden steps, the choice in a
golden panel with the hidden stars, a team summary of colored mini cards
and its strengths, and a reroll badge. One "Your team" block is shared by
the Guild, the recruitment and the ready team. The header shows the extra
golden stars and the balms; the tips button is gone. On the Guild, team
quests carry a "En groupe" sign until the team is ready and the streak
badge stays readable. The race gets its own admin tab: its own opening,
the day's circuit and results, rewards by place and the watchers' skill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 09:50:35 +01:00

156 lines
9.8 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.

// 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 } 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 = {
// Suivi d'un jour pour l'administration : parcours, courses lancées et finies, places, poussière versée et adversaires.
raceAdminSummary(day = this.today) {
const zonesRow = this.db.prepare("SELECT zones_json FROM team_days WHERE day = ?").get(day);
const rows = this.db.prepare("SELECT status, race_json, place, reward FROM team_races WHERE day = ?").all(day);
const finished = rows.filter((row) => row.status === "finished");
const opponents = rows.flatMap((row) => JSON.parse(row.race_json).opponents);
return {
zones: zonesRow ? JSON.parse(zonesRow.zones_json) : null,
started: rows.length, finished: finished.length,
places: Array.from({ length: RACERS }, (_, index) => finished.filter((row) => row.place === index + 1).length),
stardust: finished.reduce((sum, row) => sum + row.reward, 0),
opponents: { players: opponents.filter((opponent) => opponent.playerId).length, watchers: opponents.filter((opponent) => !opponent.playerId).length }
};
},
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(this.settings.watcherSkill), 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();
if (!this.settings.raceEnabled) fail(409, "RACE_CLOSED", "La Course des courants est fermée pour le moment.");
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 };
})
};
}
};