mirror of
https://github.com/AmanTahiliani/box-box.git
synced 2026-12-05 14:44:41 -05:00
fix(championship): drop cancelled rounds and declare a clinched title (#110)
* fix(championship): drop cancelled rounds and declare a clinched title The championship hub counted cancelled meetings (2026 Bahrain/Saudi) as rounds, reporting 25 total / 6 left instead of 23 / 4. Title math then used 6 x 25 = 150 pts as the ceiling, so a 119-pt gap still looked "alive" after Antonelli had mathematically clinched the title. - Skip cancelled meetings and cancelled Race/Sprint sessions in both the local (query) and OpenF1 aggregation paths. - Track pending sprints and return sprints_left + max_points_left (25/race + 8/sprint) so title math is sprint-aware. - Frontend: use max_points_left for alive/out, gap annotations and the simulator; show a CHAMPION state, "has clinched" title math, and a Champion stat tile once P2 cannot catch the leader. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(championship): resolve ties on countback in title math Review feedback: - Local standings broke points ties by driver number, so a season ending level could crown the wrong driver. Order ties by FIA countback (most GP wins, then P2s, ...) before falling back to driver number. - An exact-gap lead was always treated as open. It is a clinch when the leader still wins the countback even if the rival takes every remaining GP. Every rival, not just P2, is now checked. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
21b29bec6a
commit
09bbccff93
12 files changed
+442
-36
No files matched your search
@@ -10,6 +10,7 @@ import {
|
||||
projectStandings,
|
||||
} from '../lib/simulator'
|
||||
import type { Scenario } from '../lib/simulator'
|
||||
import { maxPointsLeft } from '../lib/titleMath'
|
||||
|
||||
const STORAGE_PREFIX = 'box-box.champ.sim'
|
||||
|
||||
@@ -60,8 +61,8 @@ export function ChampionshipSimulator({ hub }: { hub: ChampionshipHub }) {
|
||||
}, [hub.season, scenario])
|
||||
|
||||
const projected = useMemo(
|
||||
() => projectStandings(hub.drivers, scenario, hub.rounds_left),
|
||||
[hub.drivers, scenario, hub.rounds_left],
|
||||
() => projectStandings(hub.drivers, scenario, hub.rounds_left, maxPointsLeft(hub)),
|
||||
[hub, scenario],
|
||||
)
|
||||
|
||||
if (hub.rounds_left <= 0 || hub.drivers.length === 0 || scenario.length === 0) {
|
||||
|
||||
@@ -122,11 +122,14 @@ export function pointsGapMeaning(
|
||||
gapToAhead: number | null | undefined,
|
||||
roundsLeft: number,
|
||||
driverAhead?: string | null,
|
||||
maxPointsLeft?: number,
|
||||
): MeaningAnnotation | null {
|
||||
if (gapToAhead == null || !Number.isFinite(gapToAhead) || gapToAhead <= 0) return null
|
||||
if (!Number.isFinite(roundsLeft) || roundsLeft <= 0) return null
|
||||
|
||||
const maxCatchable = roundsLeft * MAX_POINTS_PER_ROUND
|
||||
// Prefer the sprint-aware ceiling when the caller has it.
|
||||
const maxCatchable =
|
||||
maxPointsLeft != null && Number.isFinite(maxPointsLeft) ? maxPointsLeft : roundsLeft * MAX_POINTS_PER_ROUND
|
||||
const ahead = driverAhead?.trim() || 'ahead'
|
||||
|
||||
if (gapToAhead > maxCatchable) {
|
||||
|
||||
@@ -127,6 +127,8 @@ export function projectStandings(
|
||||
drivers: ReadonlyArray<ChampHubDriver>,
|
||||
scenario: Scenario,
|
||||
roundsLeft: number,
|
||||
/** Sprint-aware points ceiling; defaults to race wins only. */
|
||||
maxPointsLeft?: number,
|
||||
): ProjectedDriver[] {
|
||||
if (drivers.length === 0) return []
|
||||
|
||||
@@ -134,7 +136,10 @@ export function projectStandings(
|
||||
const ordered = championshipOrder(drivers)
|
||||
const leader = ordered[0]
|
||||
const leaderProjected = leader.points + (extras.get(leader.driver_number) ?? 0)
|
||||
const maxRemaining = MAX_POINTS_PER_ROUND * Math.max(0, roundsLeft)
|
||||
const maxRemaining =
|
||||
maxPointsLeft != null && Number.isFinite(maxPointsLeft)
|
||||
? Math.max(0, maxPointsLeft)
|
||||
: MAX_POINTS_PER_ROUND * Math.max(0, roundsLeft)
|
||||
|
||||
const rows = ordered.map((driver, i) => {
|
||||
const simPoints = extras.get(driver.driver_number) ?? 0
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// Title math shared by the championship views. Pure functions only.
|
||||
|
||||
import type { ChampHubDriver, ChampionshipHub } from '../types'
|
||||
|
||||
/** Max points one driver can take from a Grand Prix / a Sprint (2025+ rules). */
|
||||
export const MAX_RACE_POINTS = 25
|
||||
export const MAX_SPRINT_POINTS = 8
|
||||
|
||||
/**
|
||||
* Most points any one driver can still score this season. Prefers the
|
||||
* server's sprint-aware `max_points_left`; falls back to race wins only for
|
||||
* older API responses that do not carry it.
|
||||
*/
|
||||
export function maxPointsLeft(hub: Pick<ChampionshipHub, 'rounds_left' | 'max_points_left' | 'sprints_left'>): number {
|
||||
if (typeof hub.max_points_left === 'number' && Number.isFinite(hub.max_points_left)) {
|
||||
return Math.max(0, hub.max_points_left)
|
||||
}
|
||||
const rounds = Math.max(0, hub.rounds_left || 0)
|
||||
const sprints = Math.max(0, hub.sprints_left || 0)
|
||||
return rounds * MAX_RACE_POINTS + sprints * MAX_SPRINT_POINTS
|
||||
}
|
||||
|
||||
/** Grand Prix finishing-position counts (position -> count) from round_positions. */
|
||||
function finishCounts(positions: ReadonlyArray<number> | undefined): Map<number, number> {
|
||||
const counts = new Map<number, number>()
|
||||
for (const p of positions ?? []) {
|
||||
if (p > 0) counts.set(p, (counts.get(p) ?? 0) + 1)
|
||||
}
|
||||
return counts
|
||||
}
|
||||
|
||||
/**
|
||||
* True only when `leader` is guaranteed to beat `rival` on countback if the
|
||||
* rival wins every remaining Grand Prix and the leader scores nothing (the
|
||||
* only way the two can finish level when the gap equals the points left).
|
||||
* The leader's remaining finishes are unknown but outside the points, so a
|
||||
* countback decided in the leader's favour cannot be overturned by them.
|
||||
*/
|
||||
function leaderWinsWorstCaseCountback(leader: ChampHubDriver, rival: ChampHubDriver, roundsLeft: number): boolean {
|
||||
const lead = finishCounts(leader.round_positions)
|
||||
const riv = finishCounts(rival.round_positions)
|
||||
riv.set(1, (riv.get(1) ?? 0) + Math.max(0, roundsLeft))
|
||||
const maxPos = Math.max(0, ...lead.keys(), ...riv.keys())
|
||||
for (let p = 1; p <= maxPos; p++) {
|
||||
const diff = (lead.get(p) ?? 0) - (riv.get(p) ?? 0)
|
||||
if (diff !== 0) return diff > 0
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* The champion once the title is mathematically decided, else null.
|
||||
* `drivers` must be in championship order (ties already resolved by the
|
||||
* server's countback). Decided when the season is over, or when no rival can
|
||||
* catch the leader: every rival is further behind than the points left, or
|
||||
* exactly that far behind but certain to lose the countback.
|
||||
*/
|
||||
export function decidedChampion(
|
||||
drivers: ReadonlyArray<ChampHubDriver>,
|
||||
maxLeft: number,
|
||||
roundsLeft = 0,
|
||||
): ChampHubDriver | null {
|
||||
const [leader, ...rivals] = drivers
|
||||
if (!leader) return null
|
||||
if (maxLeft <= 0) return leader
|
||||
if (rivals.length === 0) return null
|
||||
for (const rival of rivals) {
|
||||
const gap = leader.points - rival.points
|
||||
if (gap > maxLeft) continue
|
||||
if (gap === maxLeft && leaderWinsWorstCaseCountback(leader, rival, roundsLeft)) continue
|
||||
return null
|
||||
}
|
||||
return leader
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { Meaning } from '../components/Meaning'
|
||||
import { TeammateH2H } from '../components/TeammateH2H'
|
||||
import { teammatePairs } from '../lib/h2h'
|
||||
import { pointsGapMeaning } from '../lib/meaning'
|
||||
import { decidedChampion, maxPointsLeft } from '../lib/titleMath'
|
||||
|
||||
type View = 'drivers' | 'constructors' | 'progression' | 'rivalry' | 'simulator'
|
||||
|
||||
@@ -130,7 +131,9 @@ interface BodyProps {
|
||||
function ChampionshipBody({ hub, view, setView }: BodyProps) {
|
||||
const { drivers, teams } = hub
|
||||
const leader = drivers[0]
|
||||
const remaining = hub.rounds_left * 25
|
||||
const remaining = maxPointsLeft(hub)
|
||||
const champion = decidedChampion(drivers, remaining, hub.rounds_left)
|
||||
const sprintsLeft = hub.sprints_left ?? 0
|
||||
|
||||
const enriched = useMemo<EnrichedDriver[]>(
|
||||
() =>
|
||||
@@ -149,21 +152,31 @@ function ChampionshipBody({ hub, view, setView }: BodyProps) {
|
||||
spark: sparkPoints(d.form),
|
||||
h2h: `${d.teammate_wins}–${d.teammate_losses}`,
|
||||
h2hWin: d.teammate_wins >= d.teammate_losses,
|
||||
aliveLabel: i === 0 ? 'LEADS' : alive ? 'ALIVE' : 'OUT',
|
||||
aliveColor: i === 0 ? GOLD : alive ? 'var(--green)' : 'var(--text-3)',
|
||||
aliveLabel: i === 0 ? (champion ? 'CHAMPION' : 'LEADS') : alive && !champion ? 'ALIVE' : 'OUT',
|
||||
aliveColor: i === 0 ? GOLD : alive && !champion ? 'var(--green)' : 'var(--text-3)',
|
||||
}
|
||||
}),
|
||||
[drivers, leader, remaining],
|
||||
[drivers, leader, remaining, champion],
|
||||
)
|
||||
|
||||
const aliveCount = enriched.filter((e) => e.aliveLabel === 'ALIVE' || e.aliveLabel === 'LEADS').length
|
||||
|
||||
const titleMath =
|
||||
`${aliveCount} driver${aliveCount === 1 ? '' : 's'} can still mathematically win the title. ` +
|
||||
`With ${hub.rounds_left} round${hub.rounds_left === 1 ? '' : 's'} left (max ${remaining} pts), ` +
|
||||
`${leader.name_acronym} leads ` +
|
||||
const roundsLeftText = `${hub.rounds_left} round${hub.rounds_left === 1 ? '' : 's'}`
|
||||
const sprintsLeftText = sprintsLeft > 0 ? ` + ${sprintsLeft} sprint${sprintsLeft === 1 ? '' : 's'}` : ''
|
||||
const leadText =
|
||||
(drivers[1] ? `${drivers[1].name_acronym} by ${fmtPts(leader.points - drivers[1].points)}` : 'the field') +
|
||||
(drivers[2] ? ` and ${drivers[2].name_acronym} by ${fmtPts(leader.points - drivers[2].points)}.` : '.')
|
||||
(drivers[2] ? ` and ${drivers[2].name_acronym} by ${fmtPts(leader.points - drivers[2].points)}` : '')
|
||||
|
||||
const titleMath = champion
|
||||
? hub.rounds_left > 0
|
||||
? `${champion.full_name || champion.name_acronym} has clinched the ${hub.season} Drivers' Championship. ` +
|
||||
`${champion.name_acronym} leads ${leadText} with only ${fmtPts(remaining)} pts left ` +
|
||||
`(${roundsLeftText}${sprintsLeftText}).`
|
||||
: `${champion.full_name || champion.name_acronym} is the ${hub.season} World Champion, ` +
|
||||
`finishing ahead of ${leadText}.`
|
||||
: `${aliveCount} driver${aliveCount === 1 ? '' : 's'} can still mathematically win the title. ` +
|
||||
`With ${roundsLeftText}${sprintsLeftText} left (max ${fmtPts(remaining)} pts), ` +
|
||||
`${leader.name_acronym} leads ${leadText}.`
|
||||
|
||||
const topTeam = teams[0]
|
||||
const teamGap = teams[1] ? topTeam.points - teams[1].points : 0
|
||||
@@ -177,7 +190,9 @@ function ChampionshipBody({ hub, view, setView }: BodyProps) {
|
||||
sub: teams[1] ? `+${fmtPts(teamGap)} ahead` : 'Sole entry',
|
||||
color: '#fff',
|
||||
},
|
||||
{ label: 'Title Fight', value: `${aliveCount} alive`, sub: `${hub.rounds_left} rounds remain`, color: 'var(--red)' },
|
||||
champion
|
||||
? { label: 'Champion', value: champion.name_acronym, sub: hub.rounds_left > 0 ? `Clinched · ${roundsLeftText} to spare` : 'Season complete', color: GOLD }
|
||||
: { label: 'Title Fight', value: `${aliveCount} alive`, sub: `${roundsLeftText} remain`, color: 'var(--red)' },
|
||||
{ label: 'Season Progress', value: `${seasonPct}%`, sub: `Round ${hub.round}/${hub.total_rounds}`, color: '#fff' },
|
||||
]
|
||||
|
||||
@@ -254,6 +269,7 @@ function ChampionshipBody({ hub, view, setView }: BodyProps) {
|
||||
leaderPoints={leader.points}
|
||||
titleMath={titleMath}
|
||||
roundsLeft={hub.rounds_left}
|
||||
maxPointsLeft={remaining}
|
||||
drivers={drivers}
|
||||
season={hub.season}
|
||||
/>
|
||||
@@ -286,6 +302,7 @@ function DriversView({
|
||||
leaderPoints,
|
||||
titleMath,
|
||||
roundsLeft,
|
||||
maxPointsLeft,
|
||||
drivers,
|
||||
season,
|
||||
}: {
|
||||
@@ -293,6 +310,7 @@ function DriversView({
|
||||
leaderPoints: number
|
||||
titleMath: string
|
||||
roundsLeft: number
|
||||
maxPointsLeft: number
|
||||
drivers: ChampHubDriver[]
|
||||
season: number
|
||||
}) {
|
||||
@@ -423,7 +441,7 @@ function DriversView({
|
||||
<td className="r mono champ-td-muted">{e.gapLeader}</td>
|
||||
<td className="r mono champ-td-dim">
|
||||
{(() => {
|
||||
const gapAnnotation = pointsGapMeaning(e.gapAheadNum, roundsLeft, e.driverAhead)
|
||||
const gapAnnotation = pointsGapMeaning(e.gapAheadNum, roundsLeft, e.driverAhead, maxPointsLeft)
|
||||
return (
|
||||
<Meaning
|
||||
value={e.gapAhead}
|
||||
|
||||
@@ -118,6 +118,31 @@ describe('ChampionshipPage', () => {
|
||||
expect(screen.getAllByText('~10 pts/round').length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('declares the champion once the gap exceeds the points left', async () => {
|
||||
// VER leads NOR by 40 with one round (25 pts) left and no sprints.
|
||||
mockFetchHub.mockResolvedValue({ ...hub, round: 9, rounds_left: 1, sprints_left: 0, max_points_left: 25 })
|
||||
renderPage()
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('championship')).toBeInTheDocument())
|
||||
|
||||
const titleMath = screen.getByTestId('champ-titlemath')
|
||||
expect(titleMath).toHaveTextContent('Max Verstappen has clinched the 2025 Drivers\' Championship')
|
||||
expect(titleMath).not.toHaveTextContent('can still mathematically win')
|
||||
expect(screen.getByText('CHAMPION')).toBeInTheDocument()
|
||||
expect(screen.queryByText('ALIVE')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the title open while sprint points can still close the gap', async () => {
|
||||
// 40-pt gap vs two rounds + a sprint (58 pts max): still open.
|
||||
mockFetchHub.mockResolvedValue({ ...hub, round: 8, rounds_left: 2, sprints_left: 1, max_points_left: 58 })
|
||||
renderPage()
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('championship')).toBeInTheDocument())
|
||||
|
||||
expect(screen.getByTestId('champ-titlemath')).toHaveTextContent('2 rounds + 1 sprint left (max 58 pts)')
|
||||
expect(screen.queryByText('CHAMPION')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('switches to constructors and progression views', async () => {
|
||||
renderPage()
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { decidedChampion, maxPointsLeft } from '../lib/titleMath'
|
||||
import type { ChampHubDriver } from '../types'
|
||||
|
||||
const d = (driver_number: number, points: number, round_positions: number[] = []) =>
|
||||
({ driver_number, points, round_positions }) as ChampHubDriver
|
||||
|
||||
describe('maxPointsLeft', () => {
|
||||
it('prefers the server ceiling', () => {
|
||||
expect(maxPointsLeft({ rounds_left: 4, sprints_left: 1, max_points_left: 100 })).toBe(100)
|
||||
})
|
||||
it('falls back to races plus sprints for older responses', () => {
|
||||
expect(maxPointsLeft({ rounds_left: 4 })).toBe(100)
|
||||
expect(maxPointsLeft({ rounds_left: 4, sprints_left: 2 })).toBe(116)
|
||||
})
|
||||
})
|
||||
|
||||
describe('decidedChampion', () => {
|
||||
it('clinches when P2 cannot catch the leader', () => {
|
||||
// 2026 after Mexico City: ANT 380, VER 261, 4 rounds / no sprints left.
|
||||
expect(decidedChampion([d(12, 380), d(1, 261)], 100)?.driver_number).toBe(12)
|
||||
})
|
||||
it('stays open when the gap is reachable', () => {
|
||||
expect(decidedChampion([d(12, 380), d(1, 261)], 150)).toBeNull()
|
||||
// P2 is out of reach but P3 is not.
|
||||
expect(decidedChampion([d(12, 380), d(1, 261), d(44, 300)], 100)).toBeNull()
|
||||
})
|
||||
it('clinches on an exact gap when the leader wins the worst-case countback', () => {
|
||||
// 25-pt lead, one race left. Even if the rival wins it (3 wins) the leader has 5.
|
||||
expect(decidedChampion([d(12, 125, [1, 1, 1, 1, 1]), d(1, 100, [1, 1, 2, 2, 2])], 25, 1)?.driver_number).toBe(12)
|
||||
})
|
||||
it('stays open on an exact gap when the rival could win the countback', () => {
|
||||
// Rival would reach 3 wins vs the leader's 2.
|
||||
expect(decidedChampion([d(12, 125, [1, 1, 2, 2, 2]), d(1, 100, [1, 1, 3, 3, 3])], 25, 1)).toBeNull()
|
||||
// Level on wins and every other place: still open.
|
||||
expect(decidedChampion([d(12, 125, [1, 1, 2]), d(1, 100, [1, 2])], 25, 1)).toBeNull()
|
||||
})
|
||||
it('crowns the leader once nothing is left', () => {
|
||||
expect(decidedChampion([d(12, 400), d(1, 400)], 0)?.driver_number).toBe(12)
|
||||
})
|
||||
})
|
||||
@@ -444,6 +444,10 @@ export interface ChampionshipHub {
|
||||
round: number
|
||||
total_rounds: number
|
||||
rounds_left: number
|
||||
/** Sprint sessions still to run (absent on older servers). */
|
||||
sprints_left?: number
|
||||
/** Most points one driver can still score, races + sprints (absent on older servers). */
|
||||
max_points_left?: number
|
||||
last_race: string
|
||||
round_labels: string[]
|
||||
drivers: ChampHubDriver[]
|
||||
|
||||
Reference in new issue
Block a user