Add the race screen of the daily team

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-25 22:02:57 +01:00
parent 08c3c8f6a2
commit 7ed63fff49
17 changed files with 553 additions and 9 deletions

View file

@ -16,6 +16,7 @@ import { publishCardsReserve } from "./cardsReserve.js";
import { PrivacyNotice } from "./PrivacyNotice.jsx";
import { GuildPanel } from "./GuildPanel.jsx";
import { pendingQuestCount } from "./guildQuests.js";
import { RacePanel } from "./RacePanel.jsx";
import { ShopPanel } from "./ShopPanel.jsx";
import { TeamPanel } from "./TeamPanel.jsx";
import { TransfersPanel } from "./TransfersPanel.jsx";
@ -23,7 +24,7 @@ import { TransfersPanel } from "./TransfersPanel.jsx";
// Le jeu, puis l'économie et les échanges, puis le journal : mêmes groupes séparés par un filet que l'administration.
const PLAYER_NAVIGATION = [["home", "guild", "packs", "collection"], ["shop", "transfers"], ["history", "account"]];
// Sections sans entrée de menu, ouvertes depuis une autre : le menu y désigne cette section parente.
const SUBSECTION_PARENTS = { daily: "guild", team: "guild", expeditions: "guild" };
const SUBSECTION_PARENTS = { daily: "guild", team: "guild", race: "guild", expeditions: "guild" };
const PLAYER_SECTIONS = new Set([...PLAYER_NAVIGATION.flat(), ...Object.keys(SUBSECTION_PARENTS)]);
// Ancienne adresse conservée pour les favoris : le recyclage vit désormais dans la Collection.
const PLAYER_SECTION_ALIASES = { recycling: "collection" };
@ -309,6 +310,7 @@ export function CardsPage({ siteContent, cardsConfig, playerSection = "", player
{section === "guild" && <GuildPanel catalog={catalog} state={state} content={content.guild} />}
{section === "daily" && <DailyPanel {...panelProps} content={content.daily} />}
{section === "team" && <TeamPanel {...panelProps} content={content.team} statLabels={content.expeditions.stats} />}
{section === "race" && <RacePanel {...panelProps} content={content.race} teamContent={content.team} statLabels={content.expeditions.stats} />}
{section === "expeditions" && <ExpeditionsPanel {...panelProps} content={{ ...content.expeditions, cardSheet: content.cardSheet }} joinId={decodeURIComponent(playerSubsection)} />}
{section === "packs" && <PackPanel {...panelProps} content={content.packs} reserveContent={content.home} />}
{section === "collection" && <CollectionPanel {...panelProps} headingContent={content.collection} recyclingContent={content.recycling} onStartTransfer={startTransfer} />}

View file

@ -53,7 +53,8 @@ function ExpeditionsQuest({ summary, pending, content, now }) {
}
// Tuile de chaque type de quête, choisie par l'identifiant donné dans guildQuests.
const TEAM_COVER = "/static/img/cards/watchers-logbooks/rare/light_currents.webp";
const TEAM_COVER = "/static/img/cards/watchers-logbooks/legendary/watchers_guide_magpie.webp";
const RACE_COVER = "/static/img/cards/watchers-logbooks/rare/light_currents.webp";
// Équipe du jour : recruter, reprendre un recrutement, ou revoir son équipe.
function TeamQuest({ summary: team, pending, content }) {
@ -75,7 +76,25 @@ function TeamQuest({ summary: team, pending, content }) {
</article>;
}
const QUEST_TILES = { daily: DailyQuest, team: TeamQuest, expeditions: ExpeditionsQuest };
// Course des courants : une par jour, avec l'équipe du joueur.
function RaceQuest({ summary: team, pending, content }) {
return <article className="nds-card nebula-quest" data-status={team.race} aria-labelledby="nebula-quest-race-title">
<div className="nebula-quest-media">
<div className="nds-card-cover nebula-quest-cover" aria-hidden="true"><img src={RACE_COVER} alt="" /></div>
</div>
<div className="nds-card-body nebula-quest-body">
<p className="eyebrow">{content.raceKind}</p>
<h3 id="nebula-quest-race-title">{content.raceTitle}</h3>
<p>{content.raceDescription}</p>
<p className="nebula-quest-status">{{ running: content.raceRunning, finished: content.raceFinished }[team.race] || content.raceToRun}</p>
<div className="nds-card-actions">
<a className="nds-button" data-size="sm" data-variant={pending ? "primary" : "secondary"} href="#/cards/race">{team.race === "finished" ? content.raceResult : content.raceAction}</a>
</div>
</div>
</article>;
}
const QUEST_TILES = { daily: DailyQuest, team: TeamQuest, race: RaceQuest, expeditions: ExpeditionsQuest };
export function GuildPanel({ catalog, state, content }) {
// Heure d'affichage de la page, remise à jour au prochain retour d'expédition : la tuile passe alors d'elle-même au butin.

View file

@ -0,0 +1,144 @@
// Rôle : course en direct : décompte, animation des quatre coureurs, équipiers à cliquer pour donner leurs élans.
import { useCallback, useEffect, useRef, useState } from "react";
import { RACE_LENGTH } from "../../../../services/cards/race-rules.js";
import { fillTemplate } from "./dailyShare.js";
import { MaskIcon } from "./ExpeditionLabels.jsx";
import { activeHelper, advanceRace, advanceToNextChoice, allRuns, canGiveBoost, createRace, giveBoost, imageOf, nameOf, playerZone, raceOver, racerName } from "./raceRun.js";
import { RaceTrack } from "./RaceTrack.jsx";
import { SpecialtyBand } from "./TeamCompanion.jsx";
import { countText, specialtyStyle } from "./teamFormat.js";
const COUNTDOWN_MS = 3_000;
// Une image très en retard (onglet caché) n'avance pas la course d'un bond.
const MAX_FRAME_MS = 250;
const reducedMotion = () => Boolean(globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches);
// Ce que l'écran montre d'une course, hors avancée des coureurs : il ne change que quelques fois par course.
function snapshot(race) {
const { run } = race.player;
return { zone: playerZone(race), used: run.used, helpers: allRuns(race).map(activeHelper), finished: run.finishedAt !== null, over: raceOver(race) };
}
const sameSnapshot = (left, right) => left.zone === right.zone && left.finished === right.finished && left.over === right.over && left.used.length === right.used.length && left.helpers.every((helper, index) => helper === right.helpers[index]);
export function RaceLive({ catalog, race, companions, content, teamContent, statLabels, onBoost, onFinish, onOver }) {
const [stepped] = useState(reducedMotion);
// La course avance sur place, hors du rendu : React ne redessine que quand `view` change.
const raceRef = useRef(null);
const [view, setView] = useState(() => snapshot(createRace(race)));
const [countdown, setCountdown] = useState(() => (stepped ? 0 : Math.ceil(COUNTDOWN_MS / 1_000)));
const lanes = useRef([]);
const liveRef = useRef(null);
const finishSent = useRef(false);
const callbacks = useRef({});
useEffect(() => { callbacks.current = { onBoost, onFinish, onOver }; });
// Place les coureurs et met à jour l'écran si quelque chose a changé.
const show = useCallback(() => {
const current = raceRef.current;
allRuns(current).forEach((run, index) => lanes.current[index]?.style.setProperty("--progress", String(run.position / RACE_LENGTH)));
const next = snapshot(current);
setView((previous) => (sameSnapshot(previous, next) ? previous : next));
if (next.finished && !finishSent.current) {
finishSent.current = true;
callbacks.current.onFinish(current.player.run.boosts);
}
}, []);
useEffect(() => {
raceRef.current ??= createRace(race);
show();
if (stepped) return undefined;
let frame = 0;
let previous = null;
let wait = COUNTDOWN_MS;
let rest = 0;
function tick(now) {
const elapsed = previous === null ? 0 : Math.min(MAX_FRAME_MS, now - previous);
previous = now;
if (wait > 0) {
wait -= elapsed;
setCountdown(Math.max(0, Math.ceil(wait / 1_000)));
} else {
rest = advanceRace(raceRef.current, rest + elapsed);
show();
}
if (!raceOver(raceRef.current)) frame = requestAnimationFrame(tick);
}
frame = requestAnimationFrame(tick);
return () => cancelAnimationFrame(frame);
}, [race, show, stepped]);
// L'arrivée du dernier coureur passe au résultat.
useEffect(() => {
if (!view.over) return undefined;
const timer = setTimeout(() => callbacks.current.onOver(), stepped ? 0 : 700);
return () => clearTimeout(timer);
}, [view.over, stepped]);
const boost = useCallback((helper) => {
const current = raceRef.current;
if (!current || !canGiveBoost(current, helper)) return;
callbacks.current.onBoost(giveBoost(current, helper));
show();
}, [show]);
useEffect(() => { liveRef.current?.scrollIntoView({ block: "start" }); }, []);
const started = countdown === 0;
// Touches 1 à 4 : l'équipier de ce rang.
useEffect(() => {
if (!started) return undefined;
const onKey = (event) => {
if (event.altKey || event.ctrlKey || event.metaKey || event.repeat || event.target.closest?.("input, textarea, select, [contenteditable]")) return;
const helper = ["1", "2", "3", "4"].indexOf(event.key);
if (helper >= 0) boost(helper);
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [boost, started]);
function goOn() {
advanceToNextChoice(raceRef.current);
show();
}
const stat = race.zones[view.zone];
const nextStat = race.zones[view.zone + 1];
const left = race.helpers.length - view.used.length;
const helperId = (entry, index) => (view.helpers[index] >= 0 ? entry.helpers[view.helpers[index]].cardId : null);
const entries = [{ name: content.you, player: true, entry: race }, ...race.opponents.map((opponent) => ({ name: racerName(opponent, content), player: false, entry: opponent }))];
const companionOf = (cardId) => companions.find((companion) => companion.cardId === cardId);
return <div ref={liveRef} className="nebula-race-live">
<div className="nebula-race-stage">
<RaceTrack catalog={catalog} zones={race.zones} current={view.zone} statLabels={statLabels}
lanes={entries.map(({ name, player, entry }, index) => ({ name, player, cardId: entry.runner.cardId, helperId: helperId(entry, index) }))}
laneRef={(index) => (element) => { lanes.current[index] = element; }} />
{!started && <div className="nebula-race-countdown" role="status"><span>{countdown}</span></div>}
</div>
{view.finished ? <p className="nebula-race-arrived" role="status">{content.arrived}</p> : <>
<p className="nebula-race-zone" style={{ "--specialty": `var(--color-stat-${stat})` }}>
<span><MaskIcon name={stat} />{fillTemplate(content.zone, { stat: statLabels[stat], value: race.runner.stats[stat] })}</span>
<span>{nextStat ? fillTemplate(content.nextZone, { stat: statLabels[nextStat] }) : content.lastZone}</span>
</p>
<ul className="nebula-race-helpers">{race.helpers.map((helper, index) => {
const used = view.used.includes(index);
const active = view.helpers[0] === index;
const blocked = used || !started || view.helpers[0] >= 0;
const name = nameOf(catalog, helper.cardId, teamContent);
return <li key={helper.cardId}><button className="nebula-race-mate" type="button" data-active={active || undefined} data-used={(used && !active) || undefined} aria-disabled={blocked || undefined}
aria-label={fillTemplate(used ? content.helperUsed : content.helperLabel, { card: name, stat: statLabels[stat], value: helper.stats[stat] })} style={{ ...specialtyStyle(companionOf(helper.cardId) || { specialties: [] }), "--specialty": `var(--color-stat-${stat})` }} onClick={() => boost(index)}>
<span className="nebula-race-mate-art"><img src={imageOf(catalog, helper.cardId)} alt="" /><kbd aria-hidden="true">{index + 1}</kbd></span>
<SpecialtyBand companion={companionOf(helper.cardId) || { specialties: [] }} content={teamContent} statLabels={statLabels} />
<span className="nebula-race-mate-name">{name}</span>
<strong>+{helper.stats[stat]}</strong>
</button></li>;
})}</ul>
<div className="nds-toolbar nebula-race-help">
{stepped && <button className="nds-button" data-variant="primary" type="button" onClick={goOn}>{content.goOn}</button>}
<span>{left ? countText(stepped ? content.boostsLeftStepped : content.boostsLeft, left) : content.boostsDone}</span>
</div>
</>}
</div>;
}

View file

@ -0,0 +1,125 @@
// Rôle : page de la Course des courants : choix du coureur, course en direct, course interrompue et résultat.
import { useEffect, useRef, useState } from "react";
import { finishRace, loadTeam, recordRaceBoosts, startRace } from "./cardsApi.js";
import { fillTemplate, formatCountdown } from "./dailyShare.js";
import { RaceLive } from "./RaceLive.jsx";
import { imageOf, nameOf, racerName, raceRanking } from "./raceRun.js";
import { RaceZones } from "./RaceTrack.jsx";
import { formatStardust } from "./stardustFormat.js";
import { TeamCompanion } from "./TeamCompanion.jsx";
const formatTime = (milliseconds) => `${(milliseconds / 1_000).toLocaleString("fr-FR", { minimumFractionDigits: 2, maximumFractionDigits: 2 })} s`;
const placeText = (place, content) => fillTemplate(place === 1 ? content.placeFirst : content.placeOther, { place });
function RaceResult({ catalog, race, nextAt, content, teamContent, titleRef }) {
const [now] = useState(() => Date.now());
const ranking = raceRanking(race);
return <section className="nds-panel nebula-race-result" aria-labelledby="nebula-race-result-title" data-place={race.place}>
<h3 id="nebula-race-result-title" ref={titleRef} tabIndex={-1}>{placeText(race.place, content)}</h3>
<p className="nebula-race-reward">{race.reward > 0 ? fillTemplate(content.earned, { reward: formatStardust(race.reward) }) : content.noReward}</p>
<ol className="nebula-race-ranking">{ranking.map((entry, index) => <li key={entry.index} data-player={entry.player || undefined}>
<span>{index + 1}</span><img src={imageOf(catalog, entry.runner.cardId)} alt="" />
<span><strong>{entry.player ? content.you : racerName(entry, content)}</strong><small>{nameOf(catalog, entry.runner.cardId, teamContent)}</small></span>
<span>{formatTime(entry.finishedAt)}</span>
</li>)}</ol>
<p className="nebula-race-next">{fillTemplate(content.next, { time: formatCountdown(nextAt - now) })}</p>
</section>;
}
export function RacePanel({ catalog, runMutation, busy, content, teamContent, statLabels }) {
const [team, setTeam] = useState(null);
const [loadError, setLoadError] = useState("");
const [reloadKey, setReloadKey] = useState(0);
const [notice, setNotice] = useState("");
// Course lancée sur cette page : elle s'anime, puis laisse la place au résultat.
const [live, setLive] = useState(null);
const [finished, setFinished] = useState(null);
const titleRef = useRef(null);
useEffect(() => {
let active = true;
loadTeam()
.then((result) => { if (active) { setTeam(result.team); setLoadError(""); } })
.catch((error) => { if (active) setLoadError(error.message); });
return () => { active = false; };
}, [reloadKey]);
const showResult = !live && team?.race?.status === "finished";
const wasLive = useRef(false);
useEffect(() => {
if (live) wasLive.current = true;
else if (wasLive.current && showResult) titleRef.current?.focus();
}, [live, showResult]);
if (loadError) return <section className="nds-empty-state" role="alert"><h2>{content.title}</h2><p>{loadError}</p><button className="nds-button" data-variant="secondary" type="button" onClick={() => setReloadKey((key) => key + 1)}>{teamContent.retry}</button></section>;
if (!team) return <section className="nds-empty-state" aria-busy="true"><h2>{content.title}</h2></section>;
// Les refus propres à la course restent dans ce panneau ; runMutation garde le reste (erreurs réseau, solde).
async function play(action) {
setNotice("");
const result = await runMutation(async () => {
try {
return await action();
} catch (error) {
if (/^(RACE|TEAM)_/.test(String(error.code || ""))) return { raceError: error };
throw error;
}
});
if (result?.raceError) {
setNotice(result.raceError.message);
setLive(null);
setReloadKey((key) => key + 1);
}
return result?.team || null;
}
async function start(cardId) {
const next = await play(() => startRace(team.day, cardId));
if (!next?.race) return;
setTeam(next);
setFinished(null);
setLive(next.race);
}
// L'arrivée du joueur est envoyée aussitôt ; le résultat s'affiche quand tous les coureurs sont arrivés à l'écran.
async function finish(boosts) {
const next = await play(() => finishRace(boosts));
if (next) setFinished(next);
return next;
}
async function over() {
const next = finished || await finish(null);
if (next) setTeam(next);
setLive(null);
}
async function finishInterrupted() {
const next = await finish(null);
if (next) setTeam(next);
}
const { race } = team;
const interrupted = !live && race?.status === "running";
const choosing = !live && !race && team.status === "ready" && team.enabled;
return <section className="nebula-race" aria-labelledby="nebula-race-title">
<div className="nds-section-heading nebula-section-heading">
<div><p className="eyebrow">{content.eyebrow}</p><h2 id="nebula-race-title">{content.title}</h2></div>
<div className="nebula-team-heading-actions"><a className="nds-button" data-size="sm" data-variant="secondary" href="#/cards/team">{content.toTeam}</a><a className="nds-button" data-size="sm" data-variant="secondary" href="#/cards/guild">{content.back}</a></div>
</div>
{notice && <p className="nds-inline-notice" data-variant="warning" role="status">{notice}</p>}
{live && <RaceLive key={live.day} catalog={catalog} race={live} companions={team.companions} content={content} teamContent={teamContent} statLabels={statLabels}
onBoost={(boosts) => { recordRaceBoosts(boosts).catch(() => {}); }} onFinish={finish} onOver={over} />}
{interrupted && <div className="nds-panel nebula-race-interrupted"><h3>{content.interruptedTitle}</h3><p>{content.interruptedText}</p><button className="nds-button" data-variant="primary" type="button" disabled={busy} onClick={finishInterrupted}>{content.interruptedAction}</button></div>}
{showResult && <RaceResult catalog={catalog} race={race} nextAt={team.nextAt} content={content} teamContent={teamContent} titleRef={titleRef} />}
{!live && !race && !choosing && <div className="nds-empty-state"><p>{team.enabled ? content.needTeam : teamContent.closed}</p>{team.enabled && <a className="nds-button" data-variant="primary" href="#/cards/team">{content.recruitFirst}</a>}</div>}
{choosing && <>
<p className="nebula-race-intro">{content.intro}</p>
<RaceZones zones={team.zones} statLabels={statLabels} />
<section className="nebula-race-choice" aria-labelledby="nebula-race-choice-title">
<h3 id="nebula-race-choice-title">{content.chooseTitle}</h3>
<ul className="nebula-team-list">{team.companions.map((companion) => <li key={companion.cardId}><TeamCompanion catalog={catalog} companion={companion} content={{ ...teamContent, recruitLabel: content.chooseLabel }} statLabels={statLabels} disabled={busy} actionLabel={content.chooseAction} onSelect={() => start(companion.cardId)} /></li>)}</ul>
</section>
</>}
</section>;
}

View file

@ -0,0 +1,24 @@
// Rôle : dessine le parcours d'une course et les coureurs sur leurs couloirs.
import { MaskIcon } from "./ExpeditionLabels.jsx";
import { imageOf } from "./raceRun.js";
export function RaceZones({ zones, current = -1, statLabels }) {
return <ol className="nebula-race-zones">{zones.map((stat, index) => <li key={index} style={{ "--specialty": `var(--color-stat-${stat})` }} data-current={index === current || undefined} aria-current={index === current ? "step" : undefined}>
<MaskIcon name={stat} /><span>{statLabels[stat]}</span>
</li>)}</ol>;
}
// `lanes` : [{ name, player, cardId, helperId }] ; `laneRef(index)` reçoit l'élément du coureur, dont la page règle l'avancée.
export function RaceTrack({ catalog, zones, current, lanes, laneRef, statLabels }) {
return <div className="nebula-race-track">
<RaceZones zones={zones} current={current} statLabels={statLabels} />
{lanes.map((lane, index) => <div key={index} className="nebula-race-lane" data-player={lane.player || undefined}>
<div className="nebula-race-ground" aria-hidden="true">{zones.map((stat, zone) => <i key={zone} style={{ "--specialty": `var(--color-stat-${stat})` }} />)}</div>
<div className="nebula-race-runner" ref={laneRef(index)} data-boosted={lane.helperId ? true : undefined}>
<img src={imageOf(catalog, lane.cardId)} alt="" />
{lane.helperId && <img className="nebula-race-helper" src={imageOf(catalog, lane.helperId)} alt="" />}
</div>
<span className="nebula-race-name">{lane.name}</span>
</div>)}
</div>;
}

View file

@ -99,7 +99,7 @@ export function TeamPanel({ catalog, state, runMutation, busy, content, statLabe
<TeamMembers catalog={catalog} companions={team.companions} powers={finishedPowers} content={content} statLabels={statLabels} />
<TeamBest companions={team.companions} content={content} statLabels={statLabels} />
<div className="nds-panel nebula-team-stars-panel"><p>{content.skyRevealed}</p><TeamSky sky={team.lastSky} content={content} /></div>
<div className="nds-toolbar nebula-team-actions"><button className="nds-button" data-variant="primary" type="button" onClick={() => setFinishedPowers(null)}>{content.readyAction}</button></div>
<div className="nds-toolbar nebula-team-actions">{team.race?.status !== "finished" && <a className="nds-button" data-variant="primary" href="#/cards/race">{content.toRace}</a>}<button className="nds-button" data-variant="secondary" type="button" onClick={() => setFinishedPowers(null)}>{content.readyAction}</button></div>
</section>}
{!recruiting && !(finishedPowers && team.status === "ready") && <>
{team.status === "ready" ? <section className="nebula-team-ready" aria-labelledby="nebula-team-current-title">
@ -107,6 +107,7 @@ export function TeamPanel({ catalog, state, runMutation, busy, content, statLabe
<p>{team.teamDay === team.maxDays ? content.lastDay : team.canRecruit ? content.keepOrRecruit : content.teamText}</p>
<TeamMembers catalog={catalog} companions={team.companions} content={content} statLabels={statLabels} />
<TeamBest companions={team.companions} content={content} statLabels={statLabels} />
{team.enabled && <div className="nds-toolbar nebula-team-actions"><a className="nds-button" data-variant={team.race?.status === "finished" ? "secondary" : "primary"} href="#/cards/race">{team.race?.status === "finished" ? content.raceResult : content.toRace}</a></div>}
</section> : <section className="nebula-team-ready" aria-labelledby="nebula-team-none-title">
<h3 id="nebula-team-none-title">{team.status === "expired" ? content.expiredTitle : content.noneTitle}</h3>
<p>{fillTemplate(team.status === "expired" ? content.expiredText : content.noneText, { max: team.maxDays })}</p>

View file

@ -116,6 +116,20 @@ export function keepTeamCompanion(cardId) {
return request("/team/keep", { method: "POST", body: JSON.stringify({ cardId }) });
}
export function startRace(day, cardId) {
return request("/team/race", { method: "POST", body: JSON.stringify({ day, cardId }) });
}
// Élans donnés jusqu'ici : [{ at, helper }], `at` en millisecondes depuis le départ.
export function recordRaceBoosts(boosts) {
return request("/team/race/boosts", { method: "POST", body: JSON.stringify({ boosts }) });
}
// Sans `boosts`, la course se termine avec ceux déjà enregistrés.
export function finishRace(boosts) {
return request("/team/race/finish", { method: "POST", body: JSON.stringify({ boosts }) });
}
// Récompense d'une victoire : "stardust" ou "star" (moins de poussière et une étoile dorée).
export function chooseDailyReward(day, choice) {
return request("/daily/reward", { method: "POST", body: JSON.stringify({ day, choice }) });

View file

@ -18,6 +18,8 @@ export function guildQuests(state, now = Date.now()) {
// L'Équipe du jour n'apparaît que si elle est ouverte, ou tant qu'un recrutement n'est pas terminé.
const team = state.team;
if (team && (team.enabled || team.status === "recruiting")) quests.push({ id: "team", pending: team.status !== "ready", summary: team });
// La Course attend une équipe ; une course commencée se termine même si l'Équipe du jour ferme.
if (team && ((team.enabled && team.status === "ready") || team.race === "running")) quests.push({ id: "race", pending: team.race !== "finished", summary: team });
const expeditions = state.expeditions;
if (expeditions && (expeditions.enabled || expeditions.running || expeditions.returned || expeditions.forming)) quests.push({ id: "expeditions", pending: expeditionsPending(expeditions, now), summary: expeditions });
return quests;

View file

@ -0,0 +1,68 @@
// Rôle : fait avancer une course à l'écran avec les règles du serveur (coureur du joueur, adversaires et leurs élans).
import { applyBoost, canBoost, startRun, STEP_MS, stepRun, zoneAt } from "../../../../services/cards/race-rules.js";
const entrant = ({ runner, helpers }) => ({ runner: runner.stats, helpers: helpers.map((helper) => helper.stats) });
// État d'une course, modifié sur place : une course avance de plusieurs pas par image, sans rendu React à chaque pas.
export function createRace(race) {
return {
zones: race.zones,
player: { ...entrant(race), run: startRun() },
opponents: race.opponents.map((opponent) => ({ ...entrant(opponent), queue: [...opponent.boosts], run: startRun() }))
};
}
export function stepRace(race) {
race.player.run = stepRun(race.player.run, race.player.runner, race.zones);
for (const opponent of race.opponents) {
while (opponent.queue.length && opponent.queue[0].at <= opponent.run.time) opponent.run = applyBoost(opponent.run, opponent.helpers, race.zones, opponent.queue.shift().helper);
opponent.run = stepRun(opponent.run, opponent.runner, race.zones);
}
}
export const allRuns = (race) => [race.player.run, ...race.opponents.map((opponent) => opponent.run)];
export const raceOver = (race) => allRuns(race).every((run) => run.finishedAt !== null);
export const playerZone = (race) => zoneAt(race.player.run.position);
export const canGiveBoost = (race, helper) => canBoost(race.player.run, race.player.helpers, helper);
export function giveBoost(race, helper) {
race.player.run = applyBoost(race.player.run, race.player.helpers, race.zones, helper);
return race.player.run.boosts;
}
// Avance d'une durée ; le reste inférieur à un pas est renvoyé pour l'image suivante.
export function advanceRace(race, duration) {
let left = duration;
while (left >= STEP_MS && !raceOver(race)) {
stepRace(race);
left -= STEP_MS;
}
return left;
}
// Mouvement réduit : avance d'un coup jusqu'à la zone suivante, la fin d'un élan ou l'arrivée du joueur, puis laisse choisir.
export function advanceToNextChoice(race) {
const zone = playerZone(race);
const boosting = () => race.player.run.time < race.player.run.boostEnd;
const wasBoosting = boosting();
do stepRace(race);
while (race.player.run.finishedAt === null && playerZone(race) === zone && !(wasBoosting && !boosting()));
if (race.player.run.finishedAt !== null) while (!raceOver(race)) stepRace(race);
}
// Équipier dont l'élan est en cours, ou -1.
export const activeHelper = (run) => (run.finishedAt === null && run.time < run.boostEnd ? run.boosts.at(-1).helper : -1);
// Classement d'une course finie : à égalité, le joueur passe devant, comme sur le serveur.
export function raceRanking(race) {
return [{ player: true, finishedAt: race.finishedAt, runner: race.runner }, ...race.opponents.map((opponent) => ({ player: false, ...opponent }))]
.map((entry, index) => ({ ...entry, index })).sort((left, right) => left.finishedAt - right.finishedAt || left.index - right.index);
}
// Nom d'un adversaire : son pseudo, une Équipe des Veilleurs ou un compte supprimé depuis.
export function racerName(entry, content) {
return entry.name || (entry.watchers ? content.watchers : content.deletedPlayer);
}
export const imageOf = (catalog, cardId) => catalog.cards.find((card) => card.id === cardId)?.image || "";
export const nameOf = (catalog, cardId, content) => catalog.cards.find((card) => card.id === cardId)?.name || content.unknownCard;