diff --git a/src/api/analysis.ts b/src/api/analysis.ts index e0e290d7..ccbfebe1 100644 --- a/src/api/analysis.ts +++ b/src/api/analysis.ts @@ -368,6 +368,9 @@ export const fetchAnalyzedMaiaGame = async ( // is saved. (A reply without is_owner, from before the backend sent it, // counts as the owner's, as every game opened then was.) isOwner: data['is_owner'] !== false, + // The PGN the backend built, with each move's clock in a game played + // with clocks (for the export). + pgn: typeof data['pgn'] === 'string' ? data['pgn'] : undefined, // UTC, with or without a zone; `ended_time` only on games finished since // the backend began keeping it. createdAt: parseTimeMs(data['created_time']), diff --git a/src/components/Board/GameplayInterface.tsx b/src/components/Board/GameplayInterface.tsx index 1ab25513..cc95d479 100644 --- a/src/components/Board/GameplayInterface.tsx +++ b/src/components/Board/GameplayInterface.tsx @@ -61,6 +61,7 @@ export const GameplayInterface: React.FC> = ( setPremove, clearPremove, premoveResetKey, + practice, } = useContext(PlayControllerContext) const { user } = useContext(AuthContext) @@ -200,6 +201,9 @@ export const GameplayInterface: React.FC> = ( ? gameStart.rating : undefined const pgnDetails = { + // A practice game's clocks can't be rebuilt from its move times: a + // takeback keeps the time used, and added time isn't kept move by move. + withClocks: !practice, date: gameStart?.gameId === game.id ? gameStart.date : undefined, timeControl: pgnTimeControl(timeControl), whiteElo: diff --git a/src/components/Common/ExportGame.test.tsx b/src/components/Common/ExportGame.test.tsx index 9b9cb060..7915b1a8 100644 --- a/src/components/Common/ExportGame.test.tsx +++ b/src/components/Common/ExportGame.test.tsx @@ -1,6 +1,6 @@ import { render, screen } from '@testing-library/react' import { Chess } from 'chess.ts' -import { GameTree } from 'src/types' +import { AnalyzedGame, GameTree } from 'src/types' import { ExportGame } from './ExportGame' const buildTree = () => { @@ -33,6 +33,7 @@ describe('ExportGame', () => { type="play" date="2026.11.06" timeControl="300+3" + withClocks whiteElo={1432} blackElo={1500} />, @@ -46,6 +47,53 @@ describe('ExportGame', () => { expect(pgn).toContain('[BlackElo "1500"]') expect(pgn).toContain('[TimeControl "300+3"]') expect(pgn).toContain('[Termination "Resign"]') - expect(pgn).toContain('1. e4 e5 (1... c5) 0-1') + // Each main-line move with its clock (the first two moves are free). + expect(pgn).toContain( + '1. e4 { [%clk 0:05:00] } 1... e5 { [%clk 0:05:00] } (1... c5) 0-1', + ) + }) + + it('leaves the clocks out of a practice game', () => { + const tree = buildTree() + render( + , + ) + const pgn = screen.getByText(/\[Event/).textContent ?? '' + expect(pgn).toContain('1. e4 e5 (1... c5) *') + }) + + it("writes an analysed game's clocks from the PGN it came with", () => { + const tree = buildTree() + render( + , + ) + const pgn = screen.getByText(/\[Event/).textContent ?? '' + expect(pgn).toContain( + '1. e4 { [%clk 0:05:00] } 1... e5 { [%clk 0:04:58] } (1... c5) *', + ) }) }) diff --git a/src/components/Common/ExportGame.tsx b/src/components/Common/ExportGame.tsx index 31f58b0c..e77a4083 100644 --- a/src/components/Common/ExportGame.tsx +++ b/src/components/Common/ExportGame.tsx @@ -5,7 +5,7 @@ import { useContext, useEffect, useState } from 'react' import { PlayedGame, AnalyzedGame, GameTree, GameNode } from 'src/types' import { TreeControllerContext } from 'src/contexts' -import { gameTreeToPgn } from 'src/lib/pgn' +import { gameTreeToPgn, mainlineClocks, pgnClocks } from 'src/lib/pgn' // What the PGN's headers say of the game when it's known. interface GameDetails { @@ -15,6 +15,8 @@ interface GameDetails { timeControl?: string whiteElo?: number blackElo?: number + /** A game played here: each move's clock, from the time it took. */ + withClocks?: boolean } interface AnalysisProps extends GameDetails { @@ -58,6 +60,7 @@ export const ExportGame: React.FC = (props) => { timeControl, whiteElo, blackElo, + withClocks, } = props const [fen, setFen] = useState('') const [pgn, setPgn] = useState('') @@ -88,19 +91,31 @@ export const ExportGame: React.FC = (props) => { elo && Number.isFinite(elo) && elo > 0 ? Math.round(elo) : undefined setPgn( - gameTreeToPgn(gameTree, { - Event: event, - Site: 'https://maiachess.com/', - Date: date, - White: whitePlayer, - Black: blackPlayer, - Result: game.termination?.result, - ID: game.id, - WhiteElo: positiveElo(whiteElo), - BlackElo: positiveElo(blackElo), - TimeControl: timeControl, - Termination: game.termination?.condition, - }), + gameTreeToPgn( + gameTree, + { + Event: event, + Site: 'https://maiachess.com/', + Date: date, + White: whitePlayer, + Black: blackPlayer, + Result: game.termination?.result, + ID: game.id, + WhiteElo: positiveElo(whiteElo), + BlackElo: positiveElo(blackElo), + TimeControl: timeControl, + Termination: game.termination?.condition, + }, + // A game played here: each move's clock, from the time it took; a + // game opened for analysis: the clocks in the PGN it came with. + type === 'play' + ? withClocks + ? mainlineClocks(gameTree, timeControl) + : undefined + : type === 'analysis' + ? pgnClocks(gameTree, (game as AnalyzedGame).pgn) + : undefined, + ), ) setFen(currentNode.fen) }, [ @@ -116,6 +131,7 @@ export const ExportGame: React.FC = (props) => { timeControl, whiteElo, blackElo, + withClocks, ]) const copy = (content: string) => { diff --git a/src/contexts/PlayControllerContext.ts b/src/contexts/PlayControllerContext.ts index fecffb41..3567b9a3 100644 --- a/src/contexts/PlayControllerContext.ts +++ b/src/contexts/PlayControllerContext.ts @@ -32,6 +32,7 @@ export interface IPlayControllerContext extends BaseTreeControllerContext { setPremove: ReturnType['setPremove'] clearPremove: ReturnType['clearPremove'] premoveResetKey: ReturnType['premoveResetKey'] + practice?: ReturnType['practice'] } const fn = () => { diff --git a/src/hooks/usePlayController/usePlayController.ts b/src/hooks/usePlayController/usePlayController.ts index 3aabfa93..c1e47cbd 100644 --- a/src/hooks/usePlayController/usePlayController.ts +++ b/src/hooks/usePlayController/usePlayController.ts @@ -275,6 +275,19 @@ export const usePlayController = ( [], ) + // The time the server's clock charged each move (its move_times), in place + // of the time the board first gave it: the player's move as this page + // timed it, and Maia's as its delay. + const syncMoveTimes = useCallback( + (times: number[]) => { + const mainLine = gameTree.getMainLine() + for (let i = 1; i < mainLine.length && i <= times.length; i++) { + mainLine[i].time = times[i - 1] + } + }, + [gameTree], + ) + const addMoveWithTime = useCallback( (moveUci: string, moveTime: number) => { const lastNode = gameTree.getLastMainlineNode() @@ -379,6 +392,7 @@ export const usePlayController = ( setOrientation: controller.setOrientation, addMoveWithTime, + syncMoveTimes, setServerTermination, syncClocks, clockExpired, diff --git a/src/hooks/usePlayController/useServerTurns.ts b/src/hooks/usePlayController/useServerTurns.ts index d7e6774c..0af70b39 100644 --- a/src/hooks/usePlayController/useServerTurns.ts +++ b/src/hooks/usePlayController/useServerTurns.ts @@ -202,6 +202,7 @@ export const useServerTurns = (options: Options) => { let moveTimeout: ReturnType | undefined const settle = (afterMaia: Chess | null) => { + controller.syncMoveTimes(game.move_times) const clocks = serverClocks(game) if (clocks) { controller.syncClocks(clocks.white, clocks.black, clocks.running) @@ -263,6 +264,7 @@ export const useServerTurns = (options: Options) => { skipped.ply === shownPly && plyRef.current === shownPly ) { + controller.syncMoveTimes(skipped.move_times) controller.syncClocks(clocks.white, clocks.black, clocks.running) } }) diff --git a/src/lib/pgn.test.ts b/src/lib/pgn.test.ts index 52d5efd4..43d47777 100644 --- a/src/lib/pgn.test.ts +++ b/src/lib/pgn.test.ts @@ -1,10 +1,13 @@ import { Chess } from 'chess.ts' import { GameTree } from 'src/types' import { + formatPgnClock, formatPgnDate, gameTreeToPgn, graftVariations, hasVariations, + mainlineClocks, + pgnClocks, parsePgnWithVariations, pgnNameOr, pgnPlayerName, @@ -235,3 +238,93 @@ describe('pgnNameOr and playerLabel', () => { expect(playerLabel('None', 'white', 'play')).toBe('Guest') }) }) + +describe('mainlineClocks', () => { + // 1. e4 e5 2. Nf3 Nc6, each move taking the time given (ms). + const timedTree = (times: number[]) => { + const tree = new GameTree(START) + tree.addMovesToMainLine(['e2e4', 'e7e5', 'g1f3', 'b8c6'], times) + return tree + } + + it('charges each move after the first two and adds the increment', () => { + const tree = timedTree([5000, 7000, 12000, 3000]) + const clocks = mainlineClocks(tree, '180+2')! + expect( + tree + .getMainLine() + .slice(1) + .map((node) => clocks.get(node)), + ).toEqual([180000, 180000, 170000, 179000]) + }) + + it('has no clocks in a game without them', () => { + expect(mainlineClocks(timedTree([1, 1, 1, 1]), '-')).toBeUndefined() + expect(mainlineClocks(timedTree([1, 1, 1, 1]), undefined)).toBeUndefined() + }) + + it('writes them as %clk comments after each main-line move', () => { + const tree = timedTree([5000, 7000, 12000, 3000]) + const pgn = gameTreeToPgn( + tree, + { Result: '*' }, + mainlineClocks(tree, '180+2'), + ) + expect(movetextOf(pgn)).toBe( + '1. e4 { [%clk 0:03:00] } 1... e5 { [%clk 0:03:00] } ' + + '2. Nf3 { [%clk 0:02:50] } 2... Nc6 { [%clk 0:02:59] } *', + ) + // And it reads back as the same game. + expect(parsePgnWithVariations(pgn)?.tree.toMoveArray()).toEqual([ + 'e2e4', + 'e7e5', + 'g1f3', + 'b8c6', + ]) + }) + + it('formats hours and runs no lower than zero', () => { + expect(formatPgnClock(3 * 3600 * 1000 + 61500)).toBe('3:01:01') + expect(formatPgnClock(-200)).toBe('0:00:00') + }) +}) + +describe('pgnClocks', () => { + const tree = () => { + const t = new GameTree(START) + t.addMovesToMainLine(['e2e4', 'e7e5', 'g1f3', 'b8c6']) + return t + } + const clocksOf = (t: GameTree, clocks?: Map) => + t + .getMainLine() + .slice(1) + .map((node) => clocks?.get(node)) + + it("reads each move's clock from the PGN's %clk comments", () => { + const t = tree() + const pgn = + '[Event "play Maia Game"]\n\n1. e4 { [%clk 0:03:00] } 1... e5 { [%clk 0:03:00] } ' + + '2. Nf3 { [%clk 0:02:50] }\n2... Nc6 { [%clk 0:02:59.5] } *' + expect(clocksOf(t, pgnClocks(t, pgn))).toEqual([ + 180000, 180000, 170000, 179500, + ]) + }) + + it('stops where the PGN and the tree part ways', () => { + const t = tree() + const pgn = + '1. e4 { [%clk 0:03:00] } 1... c5 { [%clk 0:03:00] } 2. Nf3 { [%clk 0:02:50] } *' + expect(clocksOf(t, pgnClocks(t, pgn))).toEqual([ + 180000, + undefined, + undefined, + undefined, + ]) + }) + + it('has none without a PGN or without clocks in it', () => { + expect(pgnClocks(tree(), undefined)).toBeUndefined() + expect(pgnClocks(tree(), '1. e4 e5 2. Nf3 Nc6 *')).toBeUndefined() + }) +}) diff --git a/src/lib/pgn.ts b/src/lib/pgn.ts index 007ccf69..95560230 100644 --- a/src/lib/pgn.ts +++ b/src/lib/pgn.ts @@ -1,5 +1,6 @@ import { Chess } from 'chess.ts' import { GameNode, GameTree, User } from 'src/types' +import { parsePgnMainline } from 'src/lib/humanBar' /** * PGN with variations, both ways. chess.ts reads and writes only a game's main @@ -115,12 +116,83 @@ const moveToken = (parent: GameNode, child: GameNode, withNumber: boolean) => { return withNumber ? `${number}... ${san}` : san } +/** + * Each main-line move's clock after it (ms), from the %clk comments of the + * PGN a game came with (a Lichess game, or a game played here as the backend + * keeps it). Matched to the tree move by move: the clocks stop where the two + * differ. Undefined without a PGN or without clocks in it. + */ +export const pgnClocks = ( + tree: GameTree, + pgn: string | undefined, +): Map | undefined => { + if (!pgn || !pgn.includes('%clk')) return undefined + const clocks = new Map() + let node = tree.getRoot() + for (const move of parsePgnMainline(pgn)) { + const next = node.mainChild + // Annotation glyphs ("e4!?") aren't part of the move. + if (!next || sanOf(node, next) !== move.san.replace(/[!?]+$/, '')) break + if (move.clock !== null) clocks.set(next, Math.round(move.clock * 1000)) + node = next + } + return clocks.size ? clocks : undefined +} + +// The half-moves played before the clocks start (the server's FREE_PLIES). +const FREE_PLIES = 2 + +/** A clock reading as PGN's %clk writes it: "0:04:58" (whole seconds). */ +export const formatPgnClock = (ms: number): string => { + const total = Math.max(0, Math.floor(ms / 1000)) + const hours = Math.floor(total / 3600) + const minutes = Math.floor((total % 3600) / 60) + const seconds = total % 60 + return `${hours}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}` +} + +/** + * Each main-line move's clock after it (ms): the mover's time left, from the + * time each move took. As the server keeps a game's clocks + * (src/lib/serverGames.ts): the first move of each side is free, and every + * later one is charged its time and then given the increment. `timeControl` + * is PGN's "300+3" (seconds); without clocks ("-"), no clocks. + */ +export const mainlineClocks = ( + tree: GameTree, + timeControl: string | undefined, +): Map | undefined => { + const match = timeControl?.match(/^(\d+)\+(\d+)$/) + if (!match || Number(match[1]) === 0) return undefined + const incrementMs = Number(match[2]) * 1000 + const left = { w: Number(match[1]) * 1000, b: Number(match[1]) * 1000 } + + const clocks = new Map() + let node = tree.getRoot() + let ply = 0 + while (node.mainChild) { + const mover = node.turn + node = node.mainChild + if (ply >= FREE_PLIES) { + left[mover] = Math.max(0, left[mover] - (node.time ?? 0)) + incrementMs + } + clocks.set(node, left[mover]) + ply++ + } + return clocks +} + /** * The moves from `start` on: its main continuation, each alternative in * parentheses right after the move it replaces. A node off the main line keeps * its continuation as its first child (see GameTree.addVariationNode). */ -const writeLine = (start: GameNode, numberFirst: boolean, out: string[]) => { +const writeLine = ( + start: GameNode, + numberFirst: boolean, + out: string[], + clocks?: Map, +) => { let node = start let withNumber = numberFirst for (;;) { @@ -130,11 +202,18 @@ const writeLine = (start: GameNode, numberFirst: boolean, out: string[]) => { out.push(moveToken(node, main, withNumber)) withNumber = false + const clock = clocks?.get(main) + if (clock !== undefined) { + out.push(`{ [%clk ${formatPgnClock(clock)}] }`) + // Black's move after a comment gets its number again, as Lichess + // writes it. + withNumber = true + } for (const alternative of children) { if (alternative === main) continue const line = [moveToken(node, alternative, true)] - writeLine(alternative, false, line) + writeLine(alternative, false, line, clocks) out.push(`(${line.join(' ')})`) // Black's next move after a variation needs its number again. withNumber = true @@ -149,7 +228,12 @@ const writeLine = (start: GameNode, numberFirst: boolean, out: string[]) => { * Seven Tag Roster get PGN's "unknown" values, and a game from a set-up * position gets its SetUp and FEN headers. */ -export const gameTreeToPgn = (tree: GameTree, headers: PgnHeaders): string => { +export const gameTreeToPgn = ( + tree: GameTree, + headers: PgnHeaders, + // Each main-line move's clock after it (ms), written as %clk comments. + clocks?: Map, +): string => { const root = tree.getRoot() const values = new Map() for (const [key, value] of Object.entries(headers)) { @@ -181,7 +265,7 @@ export const gameTreeToPgn = (tree: GameTree, headers: PgnHeaders): string => { }) const moves: string[] = [] - writeLine(root, true, moves) + writeLine(root, true, moves, clocks) const result = values.get('Result') ?? '*' moves.push(RESULT_TOKENS.includes(result) ? result : '*') diff --git a/src/types/analysis.ts b/src/types/analysis.ts index beac8e17..f73d00d8 100644 --- a/src/types/analysis.ts +++ b/src/types/analysis.ts @@ -32,7 +32,10 @@ export interface AnalyzedGame extends BaseGame { createdAt?: number | null /** When it ended; only stored games that finished since the backend kept it. */ endedAt?: number | null - /** Source PGN as imported (Lichess games), with [%clk] comments if any. */ + /** + * Source PGN, with [%clk] comments if any: a Lichess game's as imported, a + * stored game's as the backend built it. + */ pgn?: string } diff --git a/src/types/node.ts b/src/types/node.ts index 502de320..60036ff9 100644 --- a/src/types/node.ts +++ b/src/types/node.ts @@ -109,6 +109,11 @@ export class GameNode { get time(): number | null { return this._time } + // A game the server holds: the time its clock charged for the move, which + // can differ a little from the time the board first gave it. + set time(time: number | null) { + this._time = time + } get color(): string | null { return this._color }