Make Sokko TCG's Current Race fairer and explain each race afterwards
All checks were successful
Validate and deploy Sokko G / validate (push) Successful in 23m50s
Validate and deploy Sokko G / deploy (push) Successful in 18s

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>
This commit is contained in:
Shinuwa 2026-11-30 16:18:18 +01:00
parent 8253f74c90
commit 52df57f781
16 changed files with 603 additions and 102 deletions

View file

@ -349,6 +349,10 @@ export function createCardsApiHandler({
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/race/reset") {
json(res, 200, service.team.resetRaceForTests(session.player.id));
return true;
}
if (req.method === "POST" && url.pathname === "/api/cards/team/reset") {
json(res, 200, service.team.resetForTests(session.player.id));
return true;

View file

@ -85,25 +85,40 @@ export function boostsError(boosts, helperCount) {
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);
// Façons de jouer une course automatiquement :
// - `random` : les élans partent à des instants tirés au hasard ;
// - `fair` : comme un joueur attentif, qui donne un équipier dans une zone de sa meilleure stat, après un temps de réaction,
// et donne en fin de course ceux qui n'en trouveront plus ;
// - `skilled` : chaque équipier est gardé pour la zone restante qui lui va le mieux, sans temps de réaction.
export const AUTO_PLAYS = Object.freeze(["random", "fair", "skilled"]);
const REACTION_MS = 300;
const REACTION_SPREAD_MS = 700;
// Renvoie les élans donnés et l'arrivée.
export function autoRun({ runner, helpers }, zones, play, random) {
const order = play === "random" ? 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();
// Joueur attentif : il réagit un peu après chaque changement de zone et chaque fin d'élan.
let seen = { zone: -1, boostEnd: 0 };
let readyAt = 0;
while (run.finishedAt === null) {
if (play === "fair" && (zoneAt(run.position) !== seen.zone || run.boostEnd !== seen.boostEnd)) {
seen = { zone: zoneAt(run.position), boostEnd: run.boostEnd };
readyAt = Math.max(run.time, run.boostEnd) + REACTION_MS + random(REACTION_SPREAD_MS);
}
if (run.time >= run.boostEnd) {
if (!skilled) {
if (play === "random") {
if (times.length && run.time >= times[0]) {
times.shift();
run = applyBoost(run, helpers, zones, order.shift());
}
} else {
const choice = skilledBoost(run, helpers, zones);
const choice = play === "fair" ? (run.time >= readyAt ? fairBoost(run, helpers, zones) : null) : skilledBoost(run, helpers, zones);
if (choice !== null) run = applyBoost(run, helpers, zones, choice);
}
}
@ -112,12 +127,29 @@ export function autoRun({ runner, helpers }, zones, skilled, random) {
return run;
}
const availableHelpers = (run, helpers) => helpers.flatMap((_, index) => (run.used.includes(index) ? [] : [index]));
const strongestIn = (helpers, stat, indexes) => indexes.reduce((best, index) => (helpers[index][stat] > helpers[best][stat] ? index : best), indexes[0]);
const bestStats = (stats) => RACE_STATS.filter((stat) => stats[stat] === Math.max(...RACE_STATS.map((other) => stats[other])));
function fairBoost(run, helpers, zones) {
const zone = zoneAt(run.position);
const stat = zones[zone];
const available = availableHelpers(run, helpers);
if (!available.length) return null;
if (zone === ZONE_COUNT - 1) return strongestIn(helpers, stat, available);
const matching = available.filter((index) => bestStats(helpers[index]).includes(stat));
if (matching.length) return strongestIn(helpers, stat, matching);
const later = zones.slice(zone + 1);
const stranded = available.filter((index) => !bestStats(helpers[index]).some((best) => later.includes(best)));
return stranded.length ? strongestIn(helpers, stat, stranded) : null;
}
function skilledBoost(run, helpers, zones) {
const zone = zoneAt(run.position);
const stat = zones[zone];
const available = helpers.flatMap((_, index) => (run.used.includes(index) ? [] : [index]));
const available = availableHelpers(run, helpers);
if (!available.length) return null;
const strongest = (indexes) => indexes.reduce((best, index) => (helpers[index][stat] > helpers[best][stat] ? index : best), indexes[0]);
const strongest = (indexes) => strongestIn(helpers, stat, indexes);
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;
@ -125,5 +157,67 @@ function skilledBoost(run, helpers, zones) {
return ready.length ? strongest(ready) : null;
}
// Meilleurs élans trouvés pour un coureur et ses équipiers : chaque équipier est essayé dans chaque zone, donné dès qu'il peut
// l'être ou au dernier moment (l'élan garde la valeur de sa zone et profite à la suivante, où le coureur va peut-être moins vite).
// Pour le bilan d'une course. Chaque essai s'estime d'un changement de zone ou de fin d'élan au suivant, sans pas fixes ; les
// meilleurs, mis au pas, sont rejoués exactement avec `replayRun`, et le plus rapide l'emporte.
const BEST_CANDIDATES = 40;
export function bestBoosts({ runner, helpers }, zones) {
const speeds = zones.map((stat) => runnerSpeed(runner, stat));
const lifts = helpers.map((helper) => zones.map((stat) => boostSpeed(helper, stat)));
const count = helpers.length;
const choices = ZONE_COUNT * 2;
const zoneOf = Array(count).fill(0);
const late = Array(count).fill(false);
// Meilleurs essais estimés, du plus rapide au plus lent.
const kept = [];
const limit = () => (kept.length < BEST_CANDIDATES ? Infinity : kept.at(-1).time);
for (let plan = 0; plan < choices ** count; plan += 1) {
for (let index = 0, rest = plan; index < count; index += 1, rest = Math.floor(rest / choices)) {
zoneOf[index] = rest % ZONE_COUNT;
late[index] = rest % choices >= ZONE_COUNT;
}
const used = Array(count).fill(false);
const boosts = [];
let time = 0;
let zone = 0;
let position = 0;
let boostEnd = 0;
let lift = 0;
const give = (wantLate, at) => {
const helper = zoneOf.findIndex((wanted, index) => wanted === zone && late[index] === wantLate && !used[index]);
if (helper < 0) return;
used[helper] = true;
boosts.push({ at, helper });
boostEnd = time + BOOST_MS;
lift = lifts[helper][zone];
};
const worst = limit();
while (zone < ZONE_COUNT && time < worst) {
if (time >= boostEnd) give(false, Math.ceil(time / STEP_MS) * STEP_MS);
const speed = (speeds[zone] + (time < boostEnd ? lift : 0)) / 1_000;
const toEdge = ((zone + 1) * ZONE_LENGTH - position) / speed;
if (time < boostEnd && boostEnd - time < toEdge) {
position += speed * (boostEnd - time);
time = boostEnd;
} else {
time += toEdge;
// Au dernier moment : au pas d'avant la sortie de zone, pour être encore dans la zone au rejeu.
if (time >= boostEnd && zone < ZONE_COUNT - 1) give(true, Math.max(0, Math.floor(time / STEP_MS) * STEP_MS - STEP_MS));
zone += 1;
position = zone * ZONE_LENGTH;
}
}
if (time < worst) {
const slower = kept.findIndex((other) => other.time > time);
kept.splice(slower < 0 ? kept.length : slower, 0, { time, boosts });
if (kept.length > BEST_CANDIDATES) kept.pop();
}
}
const finish = (boosts) => replayRun({ runner, helpers, boosts }, zones).finishedAt;
return kept.map(({ boosts }) => ({ boosts, finishedAt: finish(boosts) })).reduce((best, other) => (other.finishedAt < best.finishedAt ? other : best), { boosts: [], finishedAt: finish([]) }).boosts;
}
// Place du joueur (1 à RACERS) : à égalité, il passe devant.
export const placeOf = (finishedAt, others) => 1 + others.filter((other) => other < finishedAt).length;

View file

@ -1,6 +1,6 @@
// 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 { 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.
@ -30,7 +30,7 @@ export const raceMethods = {
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 }
opponents: { players: opponents.filter((opponent) => opponent.playerId).length, ghosts: opponents.filter((opponent) => opponent.ghost).length, watchers: opponents.filter((opponent) => !opponent.playerId).length }
};
},
@ -45,21 +45,28 @@ export const raceMethods = {
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é).
// 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 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 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, zones, skill, this.random, this.settings.recruitment), skilled: level === "strong" });
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, companions, skilled }) => {
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, skilled, this.random);
const run = autoRun(statsOf(entrant), zones, play, this.random);
return { playerId: opponentId, ...entrant, boosts: run.boosts, finishedAt: run.finishedAt };
});
},
@ -149,7 +156,7 @@ export const raceMethods = {
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 };
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 };
})
};
}

View file

@ -265,6 +265,14 @@ export class TeamService {
return this.result(playerId);
}
// Développement : efface les courses du joueur (en cours ou finies) et garde son équipe, pour recourir aussitôt. La poussière
// déjà gagnée reste acquise.
resetRaceForTests(playerId) {
if (!this.cards.devPerks) fail(404, "NOT_FOUND", "Remise à zéro indisponible.");
this.db.prepare("DELETE FROM team_races WHERE player_id = ?").run(playerId);
return this.result(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);