diff --git a/chros/app/globals.css b/chros/app/globals.css index df5ce95..3a9398d 100644 --- a/chros/app/globals.css +++ b/chros/app/globals.css @@ -804,6 +804,10 @@ small { background: #fff0d7; color: #a67835; } +.status-void { + background: #f3e3e1; + color: #a2564b; +} .game-tabs { display: flex; border-bottom: 1px solid var(--line); diff --git a/chros/components/MatchEditor.tsx b/chros/components/MatchEditor.tsx index ee00335..4ec0347 100644 --- a/chros/components/MatchEditor.tsx +++ b/chros/components/MatchEditor.tsx @@ -1,7 +1,7 @@ 'use client'; import type { SendCommand } from '@/lib/control-types'; -import { evaluateMatch, playerName } from '@chros/scoring'; +import { matchResult, playerName } from '@chros/scoring'; import { type ControlState, type Match } from '@chros/shared'; import { MatchControls } from './matches/MatchControls'; export const statusLabels: Record = { @@ -9,6 +9,7 @@ export const statusLabels: Record = { running: '対戦中', finished: '確定', replay: '再試合待ち', + void: '無効試合', }; export default function MatchEditor({ @@ -20,7 +21,7 @@ export default function MatchEditor({ match: Match; send: SendCommand; }) { - const result = evaluateMatch(match, state.profile); + const result = matchResult(state, match); return (
@@ -38,6 +39,11 @@ export default function MatchEditor({ 再試合 {match.attempt - 1} 回目 · 以前の結果は無効として保管しています。
)} + {result.voided && ( +
+ 棄権者を含むため無効試合です。どちらにも勝敗・得点を加算しません。 +
+ )} {result.winnerId && (
↗ @@ -45,8 +51,9 @@ export default function MatchEditor({ MATCH WINNER {playerName(state, result.winnerId)} - {result.decidedBy}で勝利 · 特殊P {result.a.special}–{result.b.special} / 合計得点{' '} - {result.a.points}–{result.b.points} + {result.forfeited + ? `${result.decidedBy} · 次戦へ進出` + : `${result.decidedBy}で勝利 · 特殊P ${result.a.special}–${result.b.special} / 合計得点 ${result.a.points}–${result.b.points}`}
diff --git a/chros/components/board/Bracket.tsx b/chros/components/board/Bracket.tsx index ce477f8..a573e14 100644 --- a/chros/components/board/Bracket.tsx +++ b/chros/components/board/Bracket.tsx @@ -1,4 +1,4 @@ -import { evaluateMatch, playerName } from '@chros/scoring'; +import { matchResult, playerName } from '@chros/scoring'; import { BRACKET_MATCHES_PER_PAGE } from '@/lib/board-pages'; import { type ControlState } from '@chros/shared'; @@ -43,7 +43,7 @@ export function Bracket({ {matches .filter((match) => match.round === round) .map((match) => { - const result = evaluateMatch(match, state.profile); + const result = matchResult(state, match); return (
@@ -54,7 +54,10 @@ export function Bracket({ const playerId = match[side]; const isWinner = result.winnerId === playerId && !!playerId; const emptySlotLabel = match.bye ? '不戦枠' : '対戦者未定'; - const pointsLabel = match.games.length ? result[side].points : '–'; + let pointsLabel: string | number = match.games.length + ? result[side].points + : '–'; + if (result.absentSides.includes(side)) pointsLabel = '棄権'; return (
{playerId ? playerName(state, playerId) : emptySlotLabel} diff --git a/chros/components/board/MatchScene.tsx b/chros/components/board/MatchScene.tsx index 5b6d375..27147bc 100644 --- a/chros/components/board/MatchScene.tsx +++ b/chros/components/board/MatchScene.tsx @@ -1,9 +1,10 @@ -import { evaluateMatch, playerName } from '@chros/scoring'; +import { matchResult, playerName, type MatchResult } from '@chros/scoring'; import { reasonLabels, type ControlState } from '@chros/shared'; import type { Match } from '@chros/shared'; -function progressLabel(match: Match, result: ReturnType) { +function progressLabel(match: Match, result: MatchResult) { + if (result.voided) return '棄権により無効試合'; if (result.winnerId) return '試合確定'; if (result.tied) return '同点 · 再試合待ち'; if (match.games.length) return `第${match.games.length}戦 終了時点`; @@ -17,7 +18,7 @@ function coolPlayerId(match: Match, gameNumber: 1 | 2) { } export function MatchScene({ state, match }: { state: ControlState; match: Match }) { - const result = evaluateMatch(match, state.profile); + const result = matchResult(state, match); return ( <>
diff --git a/chros/components/board/OverviewScenes.tsx b/chros/components/board/OverviewScenes.tsx index 585d79b..88b0fe8 100644 --- a/chros/components/board/OverviewScenes.tsx +++ b/chros/components/board/OverviewScenes.tsx @@ -1,5 +1,5 @@ import { boardPages, STANDINGS_ROWS_PER_CARD } from '@/lib/board-pages'; -import { evaluateMatch } from '@chros/scoring'; +import { matchResult } from '@chros/scoring'; import { phaseLabels, type ControlState } from '@chros/shared'; import { Bracket } from './Bracket'; @@ -7,9 +7,7 @@ import { StandingsTable } from './StandingsTable'; export function StandingsScene({ state }: { state: ControlState }) { const qualifying = state.matches.filter((match) => match.stage === 'qualifying'); - const completed = qualifying.filter( - (match) => evaluateMatch(match, state.profile).winnerId, - ).length; + const completed = qualifying.filter((match) => matchResult(state, match).settled).length; const pages = boardPages(state); return ( <> diff --git a/chros/components/console/TournamentOverview.tsx b/chros/components/console/TournamentOverview.tsx index 35604eb..a3bfb2a 100644 --- a/chros/components/console/TournamentOverview.tsx +++ b/chros/components/console/TournamentOverview.tsx @@ -1,14 +1,12 @@ 'use client'; -import { evaluateMatch } from '@chros/scoring'; +import { matchResult } from '@chros/scoring'; import { phaseLabels, type ControlState } from '@chros/shared'; export function TournamentOverview({ state }: { state: ControlState }) { const match = state.matches.find((candidate) => candidate.id === state.currentMatchId); const qualifying = state.matches.filter((candidate) => candidate.stage === 'qualifying'); - const finished = qualifying.filter( - (candidate) => evaluateMatch(candidate, state.profile).winnerId, - ).length; + const finished = qualifying.filter((candidate) => matchResult(state, candidate).settled).length; const progressPercent = qualifying.length ? (finished / qualifying.length) * 100 : 0; return (
diff --git a/chros/components/management/FinalsSetup.tsx b/chros/components/management/FinalsSetup.tsx index a6f7459..28a2284 100644 --- a/chros/components/management/FinalsSetup.tsx +++ b/chros/components/management/FinalsSetup.tsx @@ -3,7 +3,7 @@ import type { FormEvent } from 'react'; import type { ControlProps } from '@/lib/control-types'; import { suggestedQualifiers } from '@/lib/tournament'; -import { evaluateMatch, groupNames, standings } from '@chros/scoring'; +import { groupNames, matchResult, standings, withdrawalOf } from '@chros/scoring'; import { useState } from 'react'; import { useConfirmation } from '../Confirmation'; @@ -13,8 +13,7 @@ export function FinalsSetup({ state, send }: ControlProps) { const [justification, setJustification] = useState(''); const qualifying = state.matches.filter((match) => match.stage === 'qualifying'); const qualifyingComplete = - qualifying.length > 0 && - qualifying.every((match) => evaluateMatch(match, state.profile).winnerId); + qualifying.length > 0 && qualifying.every((match) => matchResult(state, match).settled); const hasTiedQualifiers = groupNames(state).some((group) => standings(state, group).some((row) => row.tied && row.rank <= state.advancePerGroup), ); @@ -59,11 +58,13 @@ export function FinalsSetup({ state, send }: ControlProps) { ) } > - {state.players.map((player) => ( - - ))} + {state.players + .filter((player) => !withdrawalOf(state, player.id)) + .map((player) => ( + + ))} ))} diff --git a/chros/components/management/Matches.tsx b/chros/components/management/Matches.tsx index 9287872..0e1def0 100644 --- a/chros/components/management/Matches.tsx +++ b/chros/components/management/Matches.tsx @@ -1,7 +1,7 @@ 'use client'; import type { ControlProps } from '@/lib/control-types'; -import { evaluateMatch, groupNames, playerName } from '@chros/scoring'; +import { groupNames, matchResult, playerName, withdrawalOf } from '@chros/scoring'; import { useState } from 'react'; import { Bracket, StandingsTable } from '../Board'; import MatchEditor, { statusLabels } from '../MatchEditor'; @@ -52,7 +52,7 @@ export function Matches({ state, send }: ControlProps) { {state.matches .filter((match) => filter === 'all' || match.stage === filter) .map((match) => { - const result = evaluateMatch(match, state.profile); + const result = matchResult(state, match); return ( @@ -135,9 +143,7 @@ export function Matches({ state, send }: ControlProps) { ) : ( evaluateMatch(match, state.profile).winnerId).length - } + key={state.matches.filter((match) => matchResult(state, match).settled).length} state={state} send={send} /> diff --git a/chros/components/management/Players.tsx b/chros/components/management/Players.tsx index 75ac717..33b53f5 100644 --- a/chros/components/management/Players.tsx +++ b/chros/components/management/Players.tsx @@ -3,7 +3,7 @@ import type { FormEvent } from 'react'; import { clientId } from '@/lib/client-id'; import type { ControlProps } from '@/lib/control-types'; -import { groupNames } from '@chros/scoring'; +import { groupNames, withdrawalOf } from '@chros/scoring'; import type { Player } from '@chros/shared'; import { useState } from 'react'; import { useConfirmation } from '../Confirmation'; @@ -13,11 +13,38 @@ export function Players({ state, send }: ControlProps) { const fresh = (): Player => ({ id: clientId(), name: '', affiliation: '', group: 'A' }); const [draft, setDraft] = useState(fresh); const editing = state.players.some((player) => player.id === draft.id); + const [withdrawing, setWithdrawing] = useState(null); + const [withdrawReason, setWithdrawReason] = useState(''); + const finalsExist = state.matches.some((match) => match.stage === 'finals'); + const canWithdraw = (player: Player) => + !finalsExist || + state.matches.some( + (match) => match.stage === 'finals' && (match.a === player.id || match.b === player.id), + ); async function removePlayer(player: Player) { if (await confirm(`${player.name}を参加者から削除しますか?`)) void send({ type: 'remove-player', playerId: player.id }); } + async function withdrawPlayer(event: FormEvent) { + event.preventDefault(); + if (!withdrawing) return; + const sent = await send({ + type: 'withdraw-player', + playerId: withdrawing.id, + reason: withdrawReason, + }); + if (sent) { + setWithdrawing(null); + setWithdrawReason(''); + } + } + + async function reinstatePlayer(player: Player) { + if (await confirm(`${player.name}の棄権を取り消し、記録済みの結果を有効に戻しますか?`)) + void send({ type: 'reinstate-player', playerId: player.id }); + } + async function createQualifyingMatches() { if ( await confirm( @@ -60,6 +87,9 @@ export function Players({ state, send }: ControlProps) { {player.name} + {withdrawalOf(state, player.id) && ( + 棄権 + )} {player.affiliation || '–'} @@ -73,6 +103,26 @@ export function Players({ state, send }: ControlProps) { > 編集 + {!!state.matches.length && + (withdrawalOf(state, player.id) ? ( + + ) : ( + canWithdraw(player) && ( + + ) + ))} {!state.matches.length && (
)} + {withdrawing && ( +
+
+ +

+ {finalsExist + ? '未決着の本戦試合を相手の不戦勝にします。決着済みの試合と予選順位は変わりません。' + : 'この参加者を含む予選試合を、記録済みのものも含めてすべて無効試合にし、順位表から外します。'} +

+
+ + +
+
+
+ )}

{state.matches.length diff --git a/chros/components/matches/MatchControls.tsx b/chros/components/matches/MatchControls.tsx index cdff313..98774b0 100644 --- a/chros/components/matches/MatchControls.tsx +++ b/chros/components/matches/MatchControls.tsx @@ -2,7 +2,7 @@ import type { FormEvent } from 'react'; import type { SendCommand } from '@/lib/control-types'; -import { playerName } from '@chros/scoring'; +import { matchResult, playerName } from '@chros/scoring'; import { type ControlState, type Match } from '@chros/shared'; import { useState } from 'react'; import GameForm from './GameForm'; @@ -39,6 +39,13 @@ export function MatchControls({ if (match.bye) { return

不戦進出として次の試合へ反映済みです。

; } + if (matchResult(state, match).absentSides.length) { + return ( +

+ 棄権者を含むため、先攻登録と得点入力はできません。取り消す場合は「参加者」画面で操作してください。 +

+ ); + } if (!match.a || !match.b) { return
前の試合の勝者が確定すると、対戦者が入ります。
; } diff --git a/chros/lib/export-results.ts b/chros/lib/export-results.ts index 06e4536..21521c2 100644 --- a/chros/lib/export-results.ts +++ b/chros/lib/export-results.ts @@ -1,4 +1,4 @@ -import { evaluateGame, evaluateMatch, playerName } from '@chros/scoring'; +import { evaluateGame, matchResult, playerName } from '@chros/scoring'; import { reasonLabels, type ControlState, type Game, type Match } from '@chros/shared'; type MatchAttempt = { @@ -54,14 +54,14 @@ function matchAttempts(match: Match): MatchAttempt[] { } function gameRow(state: ControlState, match: Match, attempt: MatchAttempt, game: Game) { - const matchResult = evaluateMatch(match, state.profile); + const result = matchResult(state, match); const gameResult = evaluateGame(game, state.profile); const secondCool = attempt.firstCool === match.a ? match.b : match.a; const coolPlayerId = game.number === 1 ? attempt.firstCool : secondCool; const hotPlayerId = coolPlayerId === match.a ? match.b : match.a; let decision = ''; - if (attempt.active && matchResult.complete) { - decision = matchResult.tied ? '再試合待ち' : matchResult.decidedBy; + if (attempt.active && result.complete) { + decision = result.tied ? '再試合待ち' : result.decidedBy; } return [ match.label, @@ -83,7 +83,7 @@ function gameRow(state: ControlState, match: Match, attempt: MatchAttempt, game: gameResult.b.points, gameResult.a.special, gameResult.b.special, - attempt.active && matchResult.winnerId ? playerName(state, matchResult.winnerId) : '', + attempt.active && result.winnerId ? playerName(state, result.winnerId) : '', decision, attempt.reason, state.profile, diff --git a/chros/lib/tournament.ts b/chros/lib/tournament.ts index 40d2d92..798a8ae 100644 --- a/chros/lib/tournament.ts +++ b/chros/lib/tournament.ts @@ -3,7 +3,7 @@ import { phaseLabels, sceneLabels } from '@chros/shared'; import { createInitialState } from './tournament/initial-state'; import { assertAllowed, findMatch } from './tournament/matches'; import { replayMatch, saveGame, startMatch } from './tournament/match-commands'; -import { removePlayer, savePlayer } from './tournament/players'; +import { reinstatePlayer, removePlayer, savePlayer, withdrawPlayer } from './tournament/players'; import { generateQualifying } from './tournament/qualifying'; import { generateFinals } from './tournament/finals'; @@ -59,6 +59,10 @@ function applyStateChange(state: ControlState, command: Command): string { return savePlayer(state, command.player); case 'remove-player': return removePlayer(state, command.playerId); + case 'withdraw-player': + return withdrawPlayer(state, command); + case 'reinstate-player': + return reinstatePlayer(state, command.playerId); case 'generate-qualifying': return generateQualifying(state); case 'generate-finals': diff --git a/chros/lib/tournament/finals.ts b/chros/lib/tournament/finals.ts index f493038..5f70462 100644 --- a/chros/lib/tournament/finals.ts +++ b/chros/lib/tournament/finals.ts @@ -1,5 +1,5 @@ import type { Command, ControlState, Match } from '@chros/shared'; -import { evaluateMatch, groupNames, playerName, standings } from '@chros/scoring'; +import { groupNames, matchResult, playerName, standings } from '@chros/scoring'; import { assertAllowed, createMatch } from './matches'; type GenerateFinals = Extract; @@ -42,8 +42,7 @@ function validateQualifiers(state: ControlState, command: GenerateFinals) { const qualifying = state.matches.filter((match) => match.stage === 'qualifying'); const qualifyingComplete = - qualifying.length > 0 && - qualifying.every((match) => evaluateMatch(match, state.profile).winnerId); + qualifying.length > 0 && qualifying.every((match) => matchResult(state, match).settled); assertAllowed(qualifyingComplete, 'すべての予選試合を確定してから本戦を作成してください。'); const suggested = suggestedQualifiers(state); @@ -129,7 +128,7 @@ export function synchronizeFinals(state: ControlState) { match.sources.forEach((sourceId, index) => { if (!sourceId) return; const source = state.matches.find((candidate) => candidate.id === sourceId)!; - const winnerId = evaluateMatch(source, state.profile).winnerId; + const winnerId = matchResult(state, source).winnerId; const side = index === 0 ? 'a' : 'b'; const changesStartedMatch = match.started && match[side] !== winnerId; assertAllowed( diff --git a/chros/lib/tournament/initial-state.ts b/chros/lib/tournament/initial-state.ts index 13ae82a..682e5b8 100644 --- a/chros/lib/tournament/initial-state.ts +++ b/chros/lib/tournament/initial-state.ts @@ -18,6 +18,7 @@ export function createInitialState(demo = true): ControlState { boardPage: 0, players: [], matches: [], + withdrawals: [], currentMatchId: null, logo: null, cueId: null, diff --git a/chros/lib/tournament/matches.ts b/chros/lib/tournament/matches.ts index ab70e79..89037ca 100644 --- a/chros/lib/tournament/matches.ts +++ b/chros/lib/tournament/matches.ts @@ -1,4 +1,5 @@ import type { ControlState, Match } from '@chros/shared'; +import { matchResult } from '@chros/scoring'; export function assertAllowed(condition: unknown, message: string): asserts condition { if (!condition) throw new Error(message); @@ -39,4 +40,8 @@ export function assertEditableMatch(state: ControlState, match: Match) { const qualifyingIsLocked = match.stage === 'qualifying' && finalsExist; assertAllowed(!qualifyingIsLocked, '本戦の組み合わせ確定後は予選結果を変更できません。'); assertAllowed(!match.bye, '不戦進出の枠には得点を入力できません。'); + assertAllowed( + !matchResult(state, match).absentSides.length, + '棄権者を含む試合は記録できません。棄権を取り消してから操作してください。', + ); } diff --git a/chros/lib/tournament/players.ts b/chros/lib/tournament/players.ts index 390f504..b446e3f 100644 --- a/chros/lib/tournament/players.ts +++ b/chros/lib/tournament/players.ts @@ -1,5 +1,6 @@ -import type { ControlState, Player } from '@chros/shared'; -import { playerName } from '@chros/scoring'; +import type { Command, ControlState, Player } from '@chros/shared'; +import { matchResult, playerName, withdrawalOf } from '@chros/scoring'; +import { synchronizeFinals } from './finals'; import { assertAllowed } from './matches'; export function savePlayer(state: ControlState, player: Player) { @@ -33,3 +34,62 @@ export function removePlayer(state: ControlState, playerId: string) { state.players = state.players.filter((player) => player.id !== playerId); return `参加者削除: ${removedName}`; } + +function isInFinals(state: ControlState, playerId: string) { + return state.matches.some( + (match) => match.stage === 'finals' && (match.a === playerId || match.b === playerId), + ); +} + +export function withdrawPlayer( + state: ControlState, + command: Extract, +) { + const player = state.players.find((candidate) => candidate.id === command.playerId); + assertAllowed(player, '参加者が見つかりません。'); + assertAllowed(state.matches.length, '組み合わせ作成前は、棄権ではなく参加者を削除してください。'); + assertAllowed(!withdrawalOf(state, player.id), 'この参加者は棄権済みです。'); + + const finalsExist = state.matches.some((match) => match.stage === 'finals'); + assertAllowed( + !finalsExist || isInFinals(state, player.id), + '本戦確定後は、本戦に出場している参加者だけを棄権にできます。', + ); + + const stage = finalsExist ? 'finals' : 'qualifying'; + state.withdrawals.push({ + playerId: player.id, + stage, + reason: command.reason, + at: new Date().toISOString(), + }); + synchronizeFinals(state); + + const affected = state.matches.filter( + (match) => match.stage === stage && (match.a === player.id || match.b === player.id), + ); + const outcome = + stage === 'qualifying' + ? `予選 ${affected.length}試合を無効` + : `相手の不戦勝: ${ + affected + .filter((match) => matchResult(state, match).forfeited) + .map((match) => match.label) + .join(', ') || '該当なし' + }`; + return `棄権: ${player.name} / ${outcome} / 理由: ${command.reason}`; +} + +export function reinstatePlayer(state: ControlState, playerId: string) { + const withdrawal = withdrawalOf(state, playerId); + assertAllowed(withdrawal, 'この参加者は棄権していません。'); + const finalsExist = state.matches.some((match) => match.stage === 'finals'); + assertAllowed( + withdrawal.stage === 'finals' || !finalsExist, + '本戦確定後は、予選中の棄権を取り消せません。', + ); + + state.withdrawals = state.withdrawals.filter((candidate) => candidate !== withdrawal); + synchronizeFinals(state); + return `棄権取消: ${playerName(state, playerId)} / 記録済みの結果を有効に戻す`; +} diff --git a/chros/public/manual/operations.html b/chros/public/manual/operations.html index 4e41158..975dc75 100644 --- a/chros/public/manual/operations.html +++ b/chros/public/manual/operations.html @@ -556,6 +556,19 @@

両戦の仕切り直し

旧結果は無効化して履歴に残ります。第1戦の得点も持ち越しません。

+
+ 参加者が来ない・途中で帰った +

棄権の記録

+
    +
  1. 「参加者」画面で、対象者の「棄権」を押します。
  2. +
  3. 欠席・体調不良などの理由を記入します。
  4. +
  5. 「理由を記録して棄権にする」を押します。
  6. +
  7. 対戦一覧で、対象の試合が「無効試合」または不戦勝になったことを確認します。
  8. +
+

+ 予選中は、その参加者を含む予選試合をすべて無効にし、順位表から外します。本戦中は、未決着の試合だけを相手の不戦勝にします。誤操作は「棄権を取消」で戻せますが、予選中の棄権は本戦作成後に取り消せません。 +

+
仕切り直しは、理由を記録するボタンを押すと実行されます @@ -853,6 +866,12 @@

困ったときに見る早見表

未記録・再試合待ちの予選、重複した進出者、各組の人数、同順位やシード変更の理由を確認します。 + + 「棄権者を含む試合は記録できません」 + + 対戦者のどちらかが棄権済みです。誤って棄権にした場合は、「参加者」画面の「棄権を取消」で記録済みの結果を有効に戻してから入力します。 + + 予選結果が保護されている diff --git a/packages/scoring/src/index.test.ts b/packages/scoring/src/index.test.ts index 13fbb31..e5b68e3 100644 --- a/packages/scoring/src/index.test.ts +++ b/packages/scoring/src/index.test.ts @@ -6,7 +6,7 @@ import { type Game, type Match, } from '@chros/shared'; -import { evaluateGame, evaluateMatch, standings } from './index'; +import { evaluateGame, evaluateMatch, matchResult, standings } from './index'; import { applyCommand, createInitialState, @@ -387,3 +387,120 @@ describe('大会進行と入力保護', () => { expect(reset.revision).toBe(3); }); }); + +describe('参加者の棄権', () => { + const involves = (match: Match, playerId: string) => [match.a, match.b].includes(playerId); + + it('予選中の棄権は記録済みを含む対戦をすべて無効にし、順位表から外す', () => { + let state = tournament(1, 4); + state = completeMatch(state, state.matches[0]!.id); + state = applyCommand(state, { type: 'withdraw-player', playerId: 'p0', reason: '体調不良' }); + + const voided = state.matches.filter((match) => involves(match, 'p0')); + expect(voided).toHaveLength(3); + for (const match of voided) + expect(matchResult(state, match)).toMatchObject({ + status: 'void', + winnerId: null, + settled: true, + }); + expect(standings(state).map((row) => row.player.id)).not.toContain('p0'); + expect(standings(state).every((row) => row.played === 0)).toBe(true); + expect(state.audit.at(-1)!.detail).toContain('予選 3試合を無効'); + }); + it('無効試合は記録できず、残りの試合だけで本戦を作成できる', () => { + let state = tournament(1, 4); + state = applyCommand(state, { type: 'withdraw-player', playerId: 'p0', reason: '欠席' }); + const voided = state.matches.find((match) => involves(match, 'p0'))!; + expect(() => + applyCommand(state, { type: 'start-match', matchId: voided.id, firstCool: 'p0' }), + ).toThrow('棄権者'); + + for (const match of state.matches.filter((match) => !involves(match, 'p0'))) + state = completeMatch(state, match.id); + expect(suggestedQualifiers(state)).toEqual(['p1', 'p2']); + const finals = applyCommand(state, { + type: 'generate-finals', + qualifiers: ['p1', 'p2'], + justification: '', + }); + expect(finals.matches.filter((match) => match.stage === 'finals')).toHaveLength(1); + }); + it('棄権を取り消すと記録済みの結果が戻り、本戦確定後は予選の棄権を取り消せない', () => { + let state = tournament(1, 3); + state = completeMatch(state, state.matches[0]!.id); + state = applyCommand(state, { type: 'withdraw-player', playerId: 'p0', reason: '欠席' }); + state = applyCommand(state, { type: 'reinstate-player', playerId: 'p0' }); + expect(standings(state).find((row) => row.player.id === 'p0')!.wins).toBe(1); + + state = applyCommand(state, { type: 'withdraw-player', playerId: 'p2', reason: '欠席' }); + state = applyCommand(state, { + type: 'generate-finals', + qualifiers: ['p0', 'p1'], + justification: '', + }); + expect(() => applyCommand(state, { type: 'reinstate-player', playerId: 'p2' })).toThrow( + '本戦確定後', + ); + }); + it('本戦中の棄権は未決着の試合を相手の不戦勝にし、予選結果と決着済みの試合は保つ', () => { + let state = withFinals(); + const semi = state.matches.filter((match) => match.stage === 'finals' && match.round === 1); + const final = () => state.matches.find((match) => match.round === 2)!; + const qualifyingBefore = JSON.stringify(standings(state)); + + state = completeMatch(state, semi[0]!.id); + state = applyCommand(state, { + type: 'withdraw-player', + playerId: semi[0]!.a!, + reason: '帰宅', + }); + expect(JSON.stringify(standings(state))).toBe(qualifyingBefore); + const decidedSemi = state.matches.find((match) => match.id === semi[0]!.id)!; + expect(matchResult(state, decidedSemi).winnerId).toBe(semi[0]!.a); + expect(matchResult(state, final())).toMatchObject({ winnerId: null, settled: false }); + + state = completeMatch(state, semi[1]!.id); + expect(matchResult(state, final())).toMatchObject({ + winnerId: semi[1]!.a, + forfeited: true, + decidedBy: '棄権による不戦勝', + }); + }); + it('未開始の本戦で棄権すると相手が次戦へ進む', () => { + let state = withFinals(); + const semi = state.matches.find((match) => match.stage === 'finals' && match.round === 1)!; + state = applyCommand(state, { type: 'withdraw-player', playerId: semi.b!, reason: '欠席' }); + expect(state.matches.find((match) => match.round === 2)!.a).toBe(semi.a); + expect(state.audit.at(-1)!.detail).toContain(semi.label); + }); + it('組み合わせ作成前・本戦に出ない参加者・二重の棄権を拒否する', () => { + const empty = createInitialState(false); + empty.players = [{ id: 'p0', name: '参加者0', affiliation: '', group: 'A' }]; + expect(() => + applyCommand(empty, { type: 'withdraw-player', playerId: 'p0', reason: '欠席' }), + ).toThrow('削除'); + + const finals = withFinals(); + const eliminated = finals.players.find( + (player) => + !finals.matches.some((match) => match.stage === 'finals' && involves(match, player.id)), + )!; + expect(() => + applyCommand(finals, { type: 'withdraw-player', playerId: eliminated.id, reason: '欠席' }), + ).toThrow('本戦に出場'); + + const withdrawn = applyCommand(tournament(), { + type: 'withdraw-player', + playerId: 'p0', + reason: '欠席', + }); + expect(() => + applyCommand(withdrawn, { type: 'withdraw-player', playerId: 'p0', reason: '欠席' }), + ).toThrow('棄権済み'); + }); + it('棄権の記録がない保存データも読み込める', () => { + const { withdrawals: _, ...legacy } = createInitialState(); + expect(stateSchema.parse(legacy).withdrawals).toEqual([]); + }); +}); diff --git a/packages/scoring/src/match.ts b/packages/scoring/src/match.ts index ace3436..158ce18 100644 --- a/packages/scoring/src/match.ts +++ b/packages/scoring/src/match.ts @@ -1,4 +1,4 @@ -import type { Game, Match, Profile } from '@chros/shared'; +import type { ControlState, Game, Match, Profile } from '@chros/shared'; type Side = 'a' | 'b'; @@ -43,18 +43,49 @@ export function evaluateGame(game: Game, profile: Profile) { }; } -function matchStatus(complete: boolean, winnerId: string | null, started: boolean) { +function matchStatus( + complete: boolean, + winnerId: string | null, + started: boolean, + voided: boolean, +) { + if (voided) return 'void'; if (complete) return winnerId ? 'finished' : 'replay'; return started ? 'running' : 'pending'; } -function decidingCriterion(match: Match, profile: Profile, primaryDifference: number) { +function decidingCriterion( + match: Match, + profile: Profile, + primaryDifference: number, + forfeited: boolean, +) { + if (forfeited) return '棄権による不戦勝'; if (match.bye) return '不戦進出'; if (!primaryDifference) return '合計得点'; return profile === 'kushiro' ? '特殊ポイント' : 'ゲーム勝数'; } -export function evaluateMatch(match: Match, profile: Profile) { +// 予選では棄権者を含む対戦をすべて無効にする。本戦では決着済みの結果を保ち、 +// 未決着の対戦だけを相手の不戦勝にする。 +function forfeitOutcome( + match: Match, + absentSides: Side[], + decidedWinnerId: string | null, +): { winnerId: string | null; voided: boolean } | null { + if (!absentSides.length) return null; + if (match.stage === 'qualifying') return { winnerId: null, voided: true }; + if (decidedWinnerId) return null; + if (absentSides.length === 2) return { winnerId: null, voided: true }; + const presentSide = absentSides[0] === 'a' ? 'b' : 'a'; + return { winnerId: match[presentSide], voided: false }; +} + +export function evaluateMatch( + match: Match, + profile: Profile, + absentPlayerIds: ReadonlySet = new Set(), +) { const totalsA: ScoreTotals = { raw: 0, points: 0, special: 0, wins: 0 }; const totalsB: ScoreTotals = { raw: 0, points: 0, special: 0, wins: 0 }; @@ -78,13 +109,55 @@ export function evaluateMatch(match: Match, profile: Profile) { winnerId = comparison > 0 ? match.a : match.b; } + const absentSides = (['a', 'b'] as const).filter((side) => { + const playerId = match[side]; + return !!playerId && absentPlayerIds.has(playerId); + }); + const forfeit = forfeitOutcome(match, absentSides, winnerId); + if (forfeit) { + // 相手が未定の本戦枠は、前の試合の勝者が入るまで待つ。 + const decided = forfeit.voided || !!forfeit.winnerId; + return { + a: forfeit.voided ? { raw: 0, points: 0, special: 0, wins: 0 } : totalsA, + b: forfeit.voided ? { raw: 0, points: 0, special: 0, wins: 0 } : totalsB, + complete: decided, + winnerId: forfeit.winnerId, + settled: decided, + voided: forfeit.voided, + forfeited: !!forfeit.winnerId, + absentSides, + tied: false, + status: matchStatus(decided, forfeit.winnerId, match.started, forfeit.voided), + decidedBy: forfeit.voided ? '棄権による無効試合' : decidingCriterion(match, profile, 0, true), + }; + } + return { a: totalsA, b: totalsB, complete, winnerId, + settled: !!winnerId, + voided: false, + forfeited: false, + absentSides, tied: complete && !winnerId, - status: matchStatus(complete, winnerId, match.started), - decidedBy: decidingCriterion(match, profile, primaryDifference), + status: matchStatus(complete, winnerId, match.started, false), + decidedBy: decidingCriterion(match, profile, primaryDifference, false), }; } + +export type MatchResult = ReturnType; + +// 予選中の棄権は予選と本戦の両方に、本戦中の棄権は本戦だけに効く。 +export function absentPlayerIds(state: ControlState, stage: Match['stage']) { + return new Set( + state.withdrawals + .filter((withdrawal) => stage === 'finals' || withdrawal.stage === 'qualifying') + .map((withdrawal) => withdrawal.playerId), + ); +} + +export function matchResult(state: ControlState, match: Match) { + return evaluateMatch(match, state.profile, absentPlayerIds(state, match.stage)); +} diff --git a/packages/scoring/src/standings.ts b/packages/scoring/src/standings.ts index 3153e34..4d66e5f 100644 --- a/packages/scoring/src/standings.ts +++ b/packages/scoring/src/standings.ts @@ -1,5 +1,5 @@ import type { ControlState, Player, Profile } from '@chros/shared'; -import { evaluateMatch } from './match'; +import { absentPlayerIds, matchResult } from './match'; export type Standing = { player: Player; @@ -18,9 +18,12 @@ function compareResults(first: Standing, second: Standing, profile: Profile) { return winsDifference || specialDifference || second.points - first.points; } +// 予選中に棄権した参加者は順位表から外し、本戦へ進めない。 export function standings(state: ControlState, group?: string): Standing[] { + const withdrawn = absentPlayerIds(state, 'qualifying'); const rows = state.players .filter((player) => group === undefined || player.group === group) + .filter((player) => !withdrawn.has(player.id)) .map((player) => ({ player, played: 0, @@ -34,7 +37,7 @@ export function standings(state: ControlState, group?: string): Standing[] { for (const match of state.matches) { if (match.stage !== 'qualifying') continue; - const result = evaluateMatch(match, state.profile); + const result = matchResult(state, match); if (!result.winnerId) continue; for (const row of rows) { @@ -73,6 +76,10 @@ export function groupNames(state: ControlState) { return [...groups].sort((first, second) => first.localeCompare(second, 'ja', { numeric: true })); } +export function withdrawalOf(state: ControlState, playerId: string | null) { + return state.withdrawals.find((withdrawal) => withdrawal.playerId === playerId) ?? null; +} + export function playerName(state: ControlState, id: string | null) { return state.players.find((player) => player.id === id)?.name ?? '対戦者未定'; } diff --git a/packages/shared/src/control.ts b/packages/shared/src/control.ts index ba67be3..39820a2 100644 --- a/packages/shared/src/control.ts +++ b/packages/shared/src/control.ts @@ -78,6 +78,14 @@ export const matchSchema = z.object({ ), }); export type Match = z.infer; +// 棄権した段階より前の結果は保つ。予選中の棄権だけが予選の対戦を無効にする。 +export const withdrawalSchema = z.object({ + playerId: id, + stage: z.enum(['qualifying', 'finals']), + reason: z.string().trim().min(1).max(300), + at: z.string(), +}); +export type Withdrawal = z.infer; export const cueSchema = z.object({ id, label, scene: z.enum(scenes), phase: z.enum(phases) }); export type Cue = z.infer; export const stateSchema = z.object({ @@ -96,6 +104,7 @@ export const stateSchema = z.object({ advancePerGroup: z.number().int().min(1).max(8), players: z.array(playerSchema).max(128), matches: z.array(matchSchema), + withdrawals: z.array(withdrawalSchema).default([]), currentMatchId: id.nullable(), logo: z.string().max(1_500_000).nullable(), cues: z.array(cueSchema).max(40), @@ -118,6 +127,12 @@ export const commandSchema = z.discriminatedUnion('type', [ z.object({ type: z.literal('replay'), matchId: id, reason: z.string().trim().min(1).max(300) }), z.object({ type: z.literal('save-player'), player: playerSchema }), z.object({ type: z.literal('remove-player'), playerId: id }), + z.object({ + type: z.literal('withdraw-player'), + playerId: id, + reason: z.string().trim().min(1).max(300), + }), + z.object({ type: z.literal('reinstate-player'), playerId: id }), z.object({ type: z.literal('generate-qualifying') }), z.object({ type: z.literal('generate-finals'),