Players kept finishing third or fourth: opponents were played better than their owners would (always the best runner, half of them with perfect boosts and no reaction time), and the Watchers recruited knowing the day's circuit, which players never see. - A player who already ran today now comes back as a ghost with their real race; other teams play like an attentive player (best runner, each teammate given in a zone of its best stat after a reaction delay). The Watchers recruit blind; only the strong one plays attentively. The administration counts the ghosts. - The rule that a boost keeps the value of the zone where it was given is now stated before and during the race. - A boosting teammate is greyed at once with "Élan donné", a 1.5 s bar and its locked value; the others dim while the player has to wait. - The result shows the place as a medal, the finish as lanes (with a gold silhouette at the best boosts), the three times, each boost placed on the circuit (dashed in the teammate's best stat when it was worth more elsewhere), a sentence per boost to place better and, when clearly faster, another runner. The best boosts are searched in the browser. - A development-only "Recourir (dev)" button erases the race and keeps the team. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
163 lines
11 KiB
JavaScript
163 lines
11 KiB
JavaScript
// 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, drawZones, 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, ghosts: opponents.filter((opponent) => opponent.ghost).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, complétées par des Équipes des Veilleurs de
|
||
// niveaux différents. Un joueur qui a déjà couru ce jour-là revient avec sa vraie course (`ghost`), sur le même circuit : on les
|
||
// prend d'abord. Les autres équipes sont jouées comme le ferait un joueur attentif, pas mieux. Les Veilleurs recrutent sans
|
||
// connaître le circuit, comme les joueurs. 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, r.race_json, r.boosts_json FROM player_teams t JOIN players p ON p.id = t.player_id
|
||
LEFT JOIN team_races r ON r.player_id = t.player_id AND r.day = ? AND r.status = 'finished'
|
||
WHERE t.player_id != ? AND t.ready_day BETWEEN ? AND ? AND p.deleted_at IS NULL ORDER BY t.player_id`).all(day, playerId, shiftDayKey(day, 1 - TEAM_DAYS), day);
|
||
const players = shuffle(rows, this.random).sort((left, right) => Number(!left.race_json) - Number(!right.race_json)).slice(0, RACERS - 1);
|
||
const opponents = players.map((row) => (row.race_json
|
||
? { playerId: row.player_id, ghost: { entrant: JSON.parse(row.race_json).entrant, boosts: JSON.parse(row.boosts_json) } }
|
||
: { playerId: row.player_id, companions: JSON.parse(row.state_json).team, play: "fair" }));
|
||
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, drawZones(this.random), skill, this.random, this.settings.recruitment), play: level === "strong" ? "fair" : "random" });
|
||
}
|
||
return shuffle(opponents, this.random).map(({ playerId: opponentId, ghost, companions, play }) => {
|
||
if (ghost) return { playerId: opponentId, ghost: true, ...ghost.entrant, boosts: ghost.boosts, finishedAt: replayRun({ ...statsOf(ghost.entrant), boosts: ghost.boosts }, zones).finishedAt };
|
||
const entrant = entrantOf(companions, bestRunner(companions.map(({ profile, power }) => companionStats(profile, power)), zones));
|
||
const run = autoRun(statsOf(entrant), zones, play, 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, ghost: Boolean(opponent.ghost), runner: opponent.runner, helpers: opponent.helpers, boosts: opponent.boosts, finishedAt: opponent.finishedAt };
|
||
})
|
||
};
|
||
}
|
||
};
|