다시 보기: 컴퓨터와 한 판·점수 문구 이전 게임도 다시 볼 수 있게(결과 비교를 순위·점수·이유·요약으로)
운영 DB 44판 중 21판이 '다시 볼 수 없어요'였던 원인: 저장 결과의 practice 표시와 새 scoreText 때문에 JSON 전체 비교가 실패. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -10,7 +10,7 @@ import { GAMES } from '@bg/games';
|
|||||||
import { openDb } from '../db';
|
import { openDb } from '../db';
|
||||||
import { Room, type Conn, type RoomConfig } from './room';
|
import { Room, type Conn, type RoomConfig } from './room';
|
||||||
import { RoomStore } from './store';
|
import { RoomStore } from './store';
|
||||||
import { Replays, rebuildGame, type ReplayInput } from './replay';
|
import { Replays, rebuildGame, sameOutcome, type ReplayInput } from './replay';
|
||||||
|
|
||||||
const json = (v: unknown) => JSON.parse(JSON.stringify(v));
|
const json = (v: unknown) => JSON.parse(JSON.stringify(v));
|
||||||
|
|
||||||
@@ -262,6 +262,24 @@ describe('replay: access and edge cases', () => {
|
|||||||
expect(await new Replays(db, GAMES, users).get(pk, 'A')).toMatchObject({ ok: false, status: 410 });
|
expect(await new Replays(db, GAMES, users).get(pk, 'A')).toMatchObject({ ok: false, status: 410 });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('practice games (marked "practice") and games recorded before final scores existed are replayable', async () => {
|
||||||
|
const { db, room, users } = omokRoom();
|
||||||
|
room.act('A', 1, { type: 'place', x: 7, y: 7 });
|
||||||
|
room.leave('B');
|
||||||
|
const pk = room.game!.gamePk;
|
||||||
|
const stored = JSON.parse(db.query<{ result_json: string }, [string]>('SELECT result_json FROM games WHERE id = ?').get(pk)!.result_json);
|
||||||
|
// As the store writes a game played with computers.
|
||||||
|
db.query('UPDATE games SET result_json = ? WHERE id = ?').run(JSON.stringify({ ...stored, practice: true }), pk);
|
||||||
|
const practice = await new Replays(db, GAMES, users).get(pk, 'A');
|
||||||
|
expect(practice.ok).toBe(true);
|
||||||
|
// A scored game recorded without scoreText gets it from the rebuilt game; a changed outcome still fails.
|
||||||
|
const scored = { ...GAMES, omok: { ...GAMES.omok!, result: (st: unknown) => { const r = GAMES.omok!.result(st); return r && { ...r, scoreText: { A: '1점', B: '0점' } }; } } };
|
||||||
|
const old = await new Replays(db, scored, users).get(pk, 'A');
|
||||||
|
if (!old.ok) throw new Error(old.error);
|
||||||
|
expect((JSON.parse(old.body) as ReplayData).result.scoreText).toEqual({ A: '1점', B: '0점' });
|
||||||
|
expect(sameOutcome({ ranking: [['A'], ['B']], summary: 'x', reason: 'normal' }, { ranking: [['B'], ['A']], summary: 'x', reason: 'normal' })).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
test('my games list: newest first, paged, with ranks and nicknames', async () => {
|
test('my games list: newest first, paged, with ranks and nicknames', async () => {
|
||||||
const { db, room, clock, users } = omokRoom();
|
const { db, room, clock, users } = omokRoom();
|
||||||
room.act('A', 1, { type: 'place', x: 7, y: 7 });
|
room.act('A', 1, { type: 'place', x: 7, y: 7 });
|
||||||
|
|||||||
@@ -41,6 +41,20 @@ function* replaySteps(def: AnyGameDefinition, input: ReplayInput): Generator<Ste
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Did the rebuilt game end the way it was recorded? Compares the outcome (ranking, scores, reason, summary), not
|
||||||
|
* labels added around it: the store marks practice games (`practice`), and `scoreText` is display wording that games
|
||||||
|
* recorded before 2026-10-11 don't have. (Comparing the raw JSON made every practice game and every older scored
|
||||||
|
* game "not replayable".)
|
||||||
|
*/
|
||||||
|
export function sameOutcome(rebuilt: GameResult, stored: GameResult): boolean {
|
||||||
|
const core = (r: GameResult) => {
|
||||||
|
const { practice: _p, scoreText: _t, ...rest } = r as GameResult & { practice?: boolean };
|
||||||
|
return JSON.stringify(rest);
|
||||||
|
};
|
||||||
|
return core(rebuilt) === core(stored);
|
||||||
|
}
|
||||||
|
|
||||||
/** Final state of a rebuilt game. */
|
/** Final state of a rebuilt game. */
|
||||||
export function rebuildGame(def: AnyGameDefinition, input: ReplayInput): unknown {
|
export function rebuildGame(def: AnyGameDefinition, input: ReplayInput): unknown {
|
||||||
let state: unknown;
|
let state: unknown;
|
||||||
@@ -233,10 +247,12 @@ export class Replays {
|
|||||||
return { ok: false, status: 410, error: '이 게임은 다시 볼 수 없어요.' };
|
return { ok: false, status: 410, error: '이 게임은 다시 볼 수 없어요.' };
|
||||||
}
|
}
|
||||||
// The rebuilt game must end exactly as recorded; otherwise the replay would show a different game.
|
// The rebuilt game must end exactly as recorded; otherwise the replay would show a different game.
|
||||||
const result = JSON.parse(g.result_json) as GameResult;
|
const stored = JSON.parse(g.result_json) as GameResult;
|
||||||
const rebuilt = def.result(built.final);
|
const rebuilt = def.result(built.final);
|
||||||
const matches = g.end_reason === 'void' ? rebuilt === null : JSON.stringify(rebuilt) === g.result_json;
|
const matches = g.end_reason === 'void' ? rebuilt === null : !!rebuilt && sameOutcome(rebuilt, stored);
|
||||||
if (!matches) return { ok: false, status: 410, error: '이 게임은 다시 볼 수 없어요.' };
|
if (!matches) return { ok: false, status: 410, error: '이 게임은 다시 볼 수 없어요.' };
|
||||||
|
// Games recorded before the result screen showed final scores get them from the rebuilt game.
|
||||||
|
const result: GameResult = rebuilt?.scoreText && !stored.scoreText ? { ...stored, scoreText: rebuilt.scoreText } : stored;
|
||||||
|
|
||||||
const ids = this.idMap(start.players, seats.map((s) => s.user_id));
|
const ids = this.idMap(start.players, seats.map((s) => s.user_id));
|
||||||
const players: Record<string, PublicUser> = {};
|
const players: Record<string, PublicUser> = {};
|
||||||
|
|||||||
@@ -126,6 +126,7 @@ export interface GameUI<V> {
|
|||||||
- **다시 만들기**: 끝난 게임을 공개된 시드 + `room_log`의 `act`/`auto` 기록으로 처음부터 다시 돌린다. `setup`(시작 시각)과 각 `apply`(그 행동을 적용한 정확한 `now`, 로그의 `at`)를 방과 똑같이 부르고 RNG도 이어서 쓰므로 결과가 방에서 끝난 상태와 한 글자도 다르지 않다. `start` 로그에 `stateVersion`을 남긴다.
|
- **다시 만들기**: 끝난 게임을 공개된 시드 + `room_log`의 `act`/`auto` 기록으로 처음부터 다시 돌린다. `setup`(시작 시각)과 각 `apply`(그 행동을 적용한 정확한 `now`, 로그의 `at`)를 방과 똑같이 부르고 RNG도 이어서 쓰므로 결과가 방에서 끝난 상태와 한 글자도 다르지 않다. `start` 로그에 `stateVersion`을 남긴다.
|
||||||
- **보이는 것**: 그 판에 앉았던 플레이어만 볼 수 있고(관전자·남은 403), 각자 게임 중에 받던 자기 `view`(있으면 `syncView`)만 받는다. 시드와 원본 로그는 서버 밖으로 나가지 않는다. 응답은 `private, no-store`.
|
- **보이는 것**: 그 판에 앉았던 플레이어만 볼 수 있고(관전자·남은 403), 각자 게임 중에 받던 자기 `view`(있으면 `syncView`)만 받는다. 시드와 원본 로그는 서버 밖으로 나가지 않는다. 응답은 `private, no-store`.
|
||||||
- **장면**: 스트리밍 행동(그림 맞히기 선)이 아닌 행동 하나가 한 장면. 첫 장면만 view 전체, 나머지는 앞 장면과의 차이(`packages/shared/src/view-patch.ts`)만 보낸다. 다시 만든 결과가 저장된 결과와 다르면 보여 주지 않는다.
|
- **장면**: 스트리밍 행동(그림 맞히기 선)이 아닌 행동 하나가 한 장면. 첫 장면만 view 전체, 나머지는 앞 장면과의 차이(`packages/shared/src/view-patch.ts`)만 보낸다. 다시 만든 결과가 저장된 결과와 다르면 보여 주지 않는다.
|
||||||
|
- **같은 결과인지 비교**(2026-10-11): 순위·점수·끝난 이유·요약만 비교한다(`sameOutcome`). 저장할 때 붙는 `practice` 표시와 화면용 `scoreText`는 뺀다. 전에는 JSON 전체를 비교해서 컴퓨터와 한 판, 그리고 점수 문구가 생기기 전에 끝난 점수 게임(라스베가스·요트·할리갈리·도블 등)이 모두 "다시 볼 수 없어요"였다(운영 DB 44판 중 21판 → 0판). 예전 게임은 다시 만든 `scoreText`를 붙여 보여 준다.
|
||||||
- **못 보는 경우**(410, 한국어 안내): 90일이 지나 로그가 지워짐, 그 뒤로 게임 규칙 버전(`stateVersion`)이 바뀜, 다시 만든 결과가 다름.
|
- **못 보는 경우**(410, 한국어 안내): 90일이 지나 로그가 지워짐, 그 뒤로 게임 규칙 버전(`stateVersion`)이 바뀜, 다시 만든 결과가 다름.
|
||||||
- **API**: `GET /api/me/games?before=&limit=`(내가 끝까지 한 게임, 최신순), `GET /api/replays/:gamePk`. 다시 만든 결과는 잠깐(10분, 32개) 캐시하고, 한 번에 하나씩 조금씩 끊어 만들어 방 처리를 막지 않는다.
|
- **API**: `GET /api/me/games?before=&limit=`(내가 끝까지 한 게임, 최신순), `GET /api/replays/:gamePk`. 다시 만든 결과는 잠깐(10분, 32개) 캐시하고, 한 번에 하나씩 조금씩 끊어 만들어 방 처리를 막지 않는다.
|
||||||
- **화면**: 게임의 `Board`/`Side`를 그대로 쓰되 읽기 전용(`act`는 아무것도 안 함, 판 안의 누르기·키 입력은 막음). 처음 / 이전 / 재생·멈춤 / 다음 / 끝 버튼, 슬라이더, "n번째 / 전체 n번", 장면 설명(누가 움직였는지, 자동 진행). 키보드 ←/→/Home/End. 들어가는 곳: 결과 화면 [▶ 다시 보기](`RoomView.lastGamePk`), 내 정보 › 내 게임 기록 [다시 보기].
|
- **화면**: 게임의 `Board`/`Side`를 그대로 쓰되 읽기 전용(`act`는 아무것도 안 함, 판 안의 누르기·키 입력은 막음). 처음 / 이전 / 재생·멈춤 / 다음 / 끝 버튼, 슬라이더, "n번째 / 전체 n번", 장면 설명(누가 움직였는지, 자동 진행). 키보드 ←/→/Home/End. 들어가는 곳: 결과 화면 [▶ 다시 보기](`RoomView.lastGamePk`), 내 정보 › 내 게임 기록 [다시 보기].
|
||||||
|
|||||||
Reference in New Issue
Block a user