- GameResult/GameResultView에 scoreText(게임별 표시 문구) 추가 - 점수가 있는 18개 게임이 결과에 최종 점수 문구를 넣음 (n점, n칩, 총자산 nP, 난 말 n개, 카드 n장 등) - 점수가 없는 게임(오목·체스·쿼리도·다빈치 코드·99·뱅·마피아·바퀴벌레 포커)은 등수만 - 결과 창 각 줄 오른쪽에 최종 점수(진하게), 그 아래 이 방 전적 - 전 게임 무작위 진행 테스트, 요트 기권 E2E, docs/06·09 갱신 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
509 lines
20 KiB
TypeScript
509 lines
20 KiB
TypeScript
/** 리버시(오셀로) (docs/games/othello.md). */
|
|
import { z } from 'zod';
|
|
import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng } from '@bg/engine';
|
|
import { CORNERS, SIZE, countDiscs, flipsFor, hasLegalMove, initialBoard, legalMoves, type Cell, type Disc } from './rules';
|
|
|
|
export type { Cell } from './rules';
|
|
export type Color = 'black' | 'white';
|
|
const DISC: Record<Color, Disc> = { black: 1, white: 2 };
|
|
const other = (c: Color): Color => (c === 'black' ? 'white' : 'black');
|
|
const COLOR_KO: Record<Color, string> = { black: '흑', white: '백' };
|
|
|
|
export const othelloOptionsSchema = z.object({
|
|
colorAssignment: z
|
|
.enum(['random', 'hostBlack', 'hostWhite', 'alternate'])
|
|
.default('random')
|
|
.meta({ title: '흑백 정하기', labels: { random: '무작위', hostBlack: '방장이 흑', hostWhite: '방장이 백', alternate: '판마다 번갈아' } }),
|
|
emptyToWinner: z.boolean().default(false).meta({ title: '끝날 때 남은 빈칸을 이긴 쪽 점수에 더하기(대회 방식)' }),
|
|
timeControl: z
|
|
.object({
|
|
kind: z
|
|
.enum(['none', 'perMove', 'fischer'])
|
|
.default('perMove')
|
|
.meta({ title: '시간 방식', labels: { none: '제한 없음', perMove: '한 수당 제한', fischer: '전체 시간 + 수당 추가' } }),
|
|
perMoveSec: z.number().int().min(5).max(600).default(30).meta({ title: '한 수 제한(초)' }),
|
|
baseSec: z.number().int().min(60).max(3600).default(300).meta({ title: '전체 시간(초)' }),
|
|
incSec: z.number().int().min(0).max(60).default(3).meta({ title: '한 수마다 추가(초)' }),
|
|
})
|
|
.default({ kind: 'perMove', perMoveSec: 30, baseSec: 300, incSec: 3 })
|
|
.meta({ title: '시간 제한' }),
|
|
timeoutPolicy: z
|
|
.enum(['autoMove', 'lose'])
|
|
.default('autoMove')
|
|
.meta({ title: '한 수 시간이 다 되면', labels: { autoMove: '자동으로 두기', lose: '시간패' } }),
|
|
autoMoveLimit: z.number().int().min(0).max(20).default(2).meta({ title: '연속 자동 착수 허용 횟수(넘으면 시간패)' }),
|
|
undo: z
|
|
.enum(['off', '1', '3', 'unlimited'])
|
|
.default('3')
|
|
.meta({ title: '무르기(1인당)', labels: { off: '안 씀', 1: '1번', 3: '3번', unlimited: '무제한' } }),
|
|
drawOffer: z.boolean().default(true).meta({ title: '무승부 제안 허용' }),
|
|
drawReofferMoves: z.number().int().min(0).max(30).default(3).meta({ title: '무승부 다시 제안까지 둬야 하는 수' }),
|
|
showLegalMoves: z.boolean().default(true).meta({ title: '둘 수 있는 칸 표시' }),
|
|
showFlipCount: z.boolean().default(false).meta({ title: '둘 수 있는 칸에 뒤집히는 개수 표시' }),
|
|
});
|
|
export type OthelloOptions = z.infer<typeof othelloOptionsSchema>;
|
|
|
|
export const othelloActionSchema = z.discriminatedUnion('type', [
|
|
z.object({ type: z.literal('place'), x: z.number().int().min(0).max(SIZE - 1), y: z.number().int().min(0).max(SIZE - 1) }),
|
|
z.object({ type: z.literal('requestUndo') }),
|
|
z.object({ type: z.literal('respondUndo'), accept: z.boolean() }),
|
|
z.object({ type: z.literal('offerDraw') }),
|
|
z.object({ type: z.literal('respondDraw'), accept: z.boolean() }),
|
|
z.object({ type: z.literal('cancelOffer') }),
|
|
z.object({ type: z.literal('resign') }),
|
|
]);
|
|
/** Client-sendable actions plus the system-only timeout action (not in the schema). */
|
|
export type OthelloAction = z.infer<typeof othelloActionSchema> | { type: 'timeout' };
|
|
|
|
export type OthelloMove =
|
|
| { kind: 'place'; color: Color; x: number; y: number; flipped: number[]; auto: boolean }
|
|
| { kind: 'pass'; color: Color };
|
|
|
|
export type OthelloReason = 'noMoves' | 'resign' | 'timeLoss' | 'drawAgreed';
|
|
|
|
export interface OthelloResult {
|
|
winner: Color | null;
|
|
reason: OthelloReason;
|
|
discs: { black: number; white: number; empty: number };
|
|
/** Disc counts with `emptyToWinner` applied (winner/draw unchanged). */
|
|
displayScore: Record<Color, number>;
|
|
summary: string;
|
|
}
|
|
|
|
export interface OthelloState {
|
|
options: OthelloOptions;
|
|
board: Cell[];
|
|
players: Record<Color, PlayerId>;
|
|
turn: Color;
|
|
phase: 'playing' | 'finished';
|
|
/** Automatic passes are recorded too (undo / replay). */
|
|
moves: OthelloMove[];
|
|
clock: { remainingMs: Record<Color, number>; turnStartedAt: number; autoMoveStreak: Record<Color, number> };
|
|
/** `plies` = number of `moves` entries removed on accept (own last place + any later entries). */
|
|
undo: { usedBy: Record<Color, number>; pending: { by: Color; plies: number } | null };
|
|
draw: { pendingBy: Color | null; lastOfferPly: Record<Color, number | null> };
|
|
result: OthelloResult | null;
|
|
}
|
|
|
|
export interface OthelloLegalMove {
|
|
x: number;
|
|
y: number;
|
|
/** Number of discs that would flip. */
|
|
flips: number;
|
|
/** Indices (y*8+x) that would flip, nearest first — for the hover preview. */
|
|
flipped: number[];
|
|
}
|
|
|
|
export interface OthelloView {
|
|
size: number;
|
|
board: Cell[];
|
|
players: Record<Color, PlayerId>;
|
|
myColor: Color | null;
|
|
turn: Color;
|
|
phase: OthelloState['phase'];
|
|
discs: { black: number; white: number; empty: number };
|
|
moves: OthelloMove[];
|
|
/** Last disc placed (passes skipped). */
|
|
lastMove: { x: number; y: number; color: Color; flipped: number[] } | null;
|
|
moveCount: number;
|
|
/** Only for the player to move; null for the waiting player and spectators. */
|
|
legalMoves: OthelloLegalMove[] | null;
|
|
showLegalMoves: boolean;
|
|
showFlipCount: boolean;
|
|
emptyToWinner: boolean;
|
|
timeControl: OthelloOptions['timeControl'];
|
|
remainingMs: Record<Color, number>;
|
|
turnStartedAt: number;
|
|
undo: { allowed: boolean; remaining: Record<Color, number | null>; pending: { by: Color; plies: number } | null };
|
|
draw: { allowed: boolean; pendingBy: Color | null };
|
|
result: OthelloResult | null;
|
|
}
|
|
|
|
const undoLimit = (o: OthelloOptions): number => (o.undo === 'off' ? 0 : o.undo === 'unlimited' ? Infinity : Number(o.undo));
|
|
const colorOf = (s: OthelloState, p: PlayerId): Color | null =>
|
|
s.players.black === p ? 'black' : s.players.white === p ? 'white' : null;
|
|
export const coordLabel = (x: number, y: number): string => `${'abcdefgh'[x]}${y + 1}`;
|
|
|
|
function finish(s: OthelloState, winner: Color | null, reason: OthelloReason): void {
|
|
s.phase = 'finished';
|
|
s.undo.pending = null;
|
|
s.draw.pendingBy = null;
|
|
const discs = countDiscs(s.board);
|
|
const displayScore = { black: discs.black, white: discs.white };
|
|
if (reason === 'noMoves' && s.options.emptyToWinner && discs.empty > 0) {
|
|
if (winner) displayScore[winner] += discs.empty;
|
|
else {
|
|
displayScore.black += discs.empty / 2;
|
|
displayScore.white += discs.empty / 2;
|
|
}
|
|
}
|
|
const score = `흑 ${displayScore.black} : 백 ${displayScore.white}`;
|
|
let summary: string;
|
|
switch (reason) {
|
|
case 'noMoves':
|
|
summary = winner ? `${COLOR_KO[winner]} 승 (${score})` : `무승부 (${score})`;
|
|
break;
|
|
case 'resign':
|
|
summary = `${COLOR_KO[other(winner!)]} 기권으로 ${COLOR_KO[winner!]} 승 (${score})`;
|
|
break;
|
|
case 'timeLoss':
|
|
summary = `${COLOR_KO[other(winner!)]} 시간패로 ${COLOR_KO[winner!]} 승 (${score})`;
|
|
break;
|
|
case 'drawAgreed':
|
|
summary = `합의 무승부 (${score})`;
|
|
break;
|
|
}
|
|
s.result = { winner, reason, discs, displayScore, summary };
|
|
}
|
|
|
|
function finishByCount(s: OthelloState): void {
|
|
const { black, white } = countDiscs(s.board);
|
|
finish(s, black > white ? 'black' : white > black ? 'white' : null, 'noMoves');
|
|
}
|
|
|
|
/**
|
|
* Place a disc (already validated), flip, then hand the turn over:
|
|
* opponent can move → their turn; else I can move → opponent passes automatically; else game over.
|
|
*/
|
|
function placeDisc(s: OthelloState, color: Color, x: number, y: number, now: number, auto: boolean, events: GameEvent[]): void {
|
|
const flipped = flipsFor(s.board, x, y, DISC[color]);
|
|
if (flipped.length === 0) throw new Error(`illegal othello move ${coordLabel(x, y)}`);
|
|
s.board[y * SIZE + x] = DISC[color];
|
|
for (const i of flipped) s.board[i] = DISC[color];
|
|
s.moves.push({ kind: 'place', color, x, y, flipped, auto });
|
|
s.undo.pending = null;
|
|
s.draw.pendingBy = null;
|
|
events.push({ type: 'placed', color, x, y, flipped, auto });
|
|
const opp = other(color);
|
|
s.clock.turnStartedAt = now;
|
|
if (hasLegalMove(s.board, DISC[opp])) {
|
|
s.turn = opp;
|
|
} else if (hasLegalMove(s.board, DISC[color])) {
|
|
s.moves.push({ kind: 'pass', color: opp });
|
|
events.push({ type: 'passed', color: opp });
|
|
s.turn = color;
|
|
} else {
|
|
finishByCount(s);
|
|
events.push({ type: 'gameEnded', winner: s.result!.winner, reason: 'noMoves' });
|
|
}
|
|
}
|
|
|
|
/** docs §8.4: a legal corner if any (random among them), else uniform over all legal moves. */
|
|
function chooseAutoMove(s: OthelloState, rng: Rng): number {
|
|
const legal = legalMoves(s.board, DISC[s.turn]).map((m) => m.i);
|
|
const corners = legal.filter((i) => CORNERS.includes(i));
|
|
const pool = corners.length ? corners : legal;
|
|
return pool[rng.int(pool.length)]!;
|
|
}
|
|
|
|
/** Rebuild the board from the move record (used by undo). */
|
|
function replayBoard(moves: readonly OthelloMove[]): Cell[] {
|
|
const b = initialBoard();
|
|
for (const m of moves) {
|
|
if (m.kind !== 'place') continue;
|
|
const flipped = flipsFor(b, m.x, m.y, DISC[m.color]);
|
|
if (flipped.length === 0) throw new Error('move record does not replay');
|
|
b[m.y * SIZE + m.x] = DISC[m.color];
|
|
for (const i of flipped) b[i] = DISC[m.color];
|
|
}
|
|
return b;
|
|
}
|
|
|
|
function pendingResponder(s: OthelloState): Color | null {
|
|
if (s.undo.pending) return other(s.undo.pending.by);
|
|
if (s.draw.pendingBy) return other(s.draw.pendingBy);
|
|
return null;
|
|
}
|
|
|
|
function lastPlaceIndex(s: OthelloState, color: Color): number {
|
|
for (let i = s.moves.length - 1; i >= 0; i--) {
|
|
const m = s.moves[i]!;
|
|
if (m.kind === 'place' && m.color === color) return i;
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
function timeLoss(s: OthelloState, loser: Color, events: GameEvent[]): void {
|
|
if (s.options.timeControl.kind === 'fischer') s.clock.remainingMs[loser] = 0;
|
|
finish(s, other(loser), 'timeLoss');
|
|
events.push({ type: 'timeLoss', color: loser });
|
|
events.push({ type: 'gameEnded', winner: other(loser), reason: 'timeLoss' });
|
|
}
|
|
|
|
export const othello: GameDefinition<OthelloState, OthelloAction, OthelloView, OthelloOptions> = {
|
|
id: 'othello',
|
|
nameKo: '오셀로',
|
|
minPlayers: 2,
|
|
maxPlayers: 2,
|
|
stateVersion: 1,
|
|
defaultOptions: othelloOptionsSchema.parse({}),
|
|
optionsSchema: othelloOptionsSchema,
|
|
actionSchema: othelloActionSchema as z.ZodType<OthelloAction>,
|
|
|
|
setup({ players, options, rng, now, gameNo }) {
|
|
const [host, guest] = players as [PlayerId, PlayerId];
|
|
let hostBlack: boolean;
|
|
switch (options.colorAssignment) {
|
|
case 'hostBlack':
|
|
hostBlack = true;
|
|
break;
|
|
case 'hostWhite':
|
|
hostBlack = false;
|
|
break;
|
|
case 'alternate':
|
|
hostBlack = (gameNo ?? 1) % 2 === 1;
|
|
break;
|
|
default:
|
|
hostBlack = rng.int(2) === 0;
|
|
}
|
|
const base = options.timeControl.baseSec * 1000;
|
|
return {
|
|
options,
|
|
board: initialBoard(),
|
|
players: hostBlack ? { black: host, white: guest } : { black: guest, white: host },
|
|
turn: 'black',
|
|
phase: 'playing',
|
|
moves: [],
|
|
clock: { remainingMs: { black: base, white: base }, turnStartedAt: now, autoMoveStreak: { black: 0, white: 0 } },
|
|
undo: { usedBy: { black: 0, white: 0 }, pending: null },
|
|
draw: { pendingBy: null, lastOfferPly: { black: null, white: null } },
|
|
result: null,
|
|
};
|
|
},
|
|
|
|
validate(s, actor, a) {
|
|
const me = colorOf(s, actor);
|
|
if (!me) return fail('이 게임의 플레이어가 아니에요.');
|
|
if (s.phase !== 'playing') return fail('게임이 이미 끝났어요.');
|
|
switch (a.type) {
|
|
case 'place': {
|
|
if (s.turn !== me) return fail('지금은 내 차례가 아니에요.');
|
|
if (a.x < 0 || a.y < 0 || a.x >= SIZE || a.y >= SIZE) return fail('판 밖이에요.');
|
|
if (s.board[a.y * SIZE + a.x] !== 0) return fail('이미 돌이 있는 칸이에요.');
|
|
if (flipsFor(s.board, a.x, a.y, DISC[me]).length === 0) return fail('여기에 두면 뒤집을 돌이 없어요.');
|
|
return ok;
|
|
}
|
|
case 'requestUndo': {
|
|
if (s.options.undo === 'off') return fail('이 방은 무르기를 쓰지 않아요.');
|
|
if (s.undo.pending || s.draw.pendingBy) return fail('이미 대기 중인 요청이 있어요.');
|
|
if (s.undo.usedBy[me] >= undoLimit(s.options)) return fail('무르기 횟수를 다 썼어요.');
|
|
if (lastPlaceIndex(s, me) < 0) return fail('아직 무를 수가 없어요.');
|
|
return ok;
|
|
}
|
|
case 'respondUndo':
|
|
if (!s.undo.pending || s.undo.pending.by === me) return fail('응답할 무르기 요청이 없어요.');
|
|
return ok;
|
|
case 'offerDraw': {
|
|
if (!s.options.drawOffer) return fail('이 방은 무승부 제안을 쓰지 않아요.');
|
|
if (s.undo.pending || s.draw.pendingBy) return fail('이미 대기 중인 요청이 있어요.');
|
|
const last = s.draw.lastOfferPly[me];
|
|
const gap = s.options.drawReofferMoves;
|
|
if (last !== null && s.moves.slice(last).filter((m) => m.kind === 'place' && m.color === me).length < gap) {
|
|
return fail(`무승부 제안은 ${gap}수를 더 둔 뒤에 다시 할 수 있어요.`);
|
|
}
|
|
return ok;
|
|
}
|
|
case 'respondDraw':
|
|
if (!s.draw.pendingBy || s.draw.pendingBy === me) return fail('응답할 무승부 제안이 없어요.');
|
|
return ok;
|
|
case 'cancelOffer':
|
|
if (s.undo.pending?.by !== me && s.draw.pendingBy !== me) return fail('취소할 요청이 없어요.');
|
|
return ok;
|
|
case 'resign':
|
|
return ok;
|
|
case 'timeout':
|
|
if (s.turn !== me) return fail('지금은 내 차례가 아니에요.');
|
|
return ok;
|
|
}
|
|
},
|
|
|
|
apply(prev, actor, a, { rng, now }) {
|
|
const s = structuredClone(prev);
|
|
const me = colorOf(s, actor)!;
|
|
const events: GameEvent[] = [];
|
|
switch (a.type) {
|
|
case 'place': {
|
|
if (s.options.timeControl.kind === 'fischer') {
|
|
s.clock.remainingMs[me] -= now - s.clock.turnStartedAt;
|
|
if (s.clock.remainingMs[me] <= 0) {
|
|
timeLoss(s, me, events);
|
|
break;
|
|
}
|
|
s.clock.remainingMs[me] += s.options.timeControl.incSec * 1000;
|
|
}
|
|
s.clock.autoMoveStreak[me] = 0;
|
|
placeDisc(s, me, a.x, a.y, now, false, events);
|
|
break;
|
|
}
|
|
case 'timeout': {
|
|
const tc = s.options.timeControl.kind;
|
|
if (tc === 'perMove' && s.options.timeoutPolicy === 'autoMove' && s.clock.autoMoveStreak[me] < s.options.autoMoveLimit) {
|
|
s.clock.autoMoveStreak[me]++;
|
|
const i = chooseAutoMove(s, rng);
|
|
events.push({ type: 'timeoutAutoMove', color: me });
|
|
placeDisc(s, me, i % SIZE, Math.floor(i / SIZE), now, true, events);
|
|
} else {
|
|
timeLoss(s, me, events);
|
|
}
|
|
break;
|
|
}
|
|
case 'requestUndo': {
|
|
s.undo.pending = { by: me, plies: s.moves.length - lastPlaceIndex(s, me) };
|
|
events.push({ type: 'undoRequested', color: me });
|
|
break;
|
|
}
|
|
case 'respondUndo': {
|
|
const { by, plies } = s.undo.pending!;
|
|
s.undo.pending = null;
|
|
if (a.accept) {
|
|
// Charge the time already used by whoever was thinking, then keep clocks as they are.
|
|
if (s.options.timeControl.kind === 'fischer') {
|
|
s.clock.remainingMs[s.turn] = Math.max(0, s.clock.remainingMs[s.turn] - (now - s.clock.turnStartedAt));
|
|
}
|
|
s.moves = s.moves.slice(0, s.moves.length - plies);
|
|
s.board = replayBoard(s.moves);
|
|
s.undo.usedBy[by]++;
|
|
s.turn = by;
|
|
s.clock.turnStartedAt = now;
|
|
for (const c of ['black', 'white'] as const) {
|
|
const last = s.draw.lastOfferPly[c];
|
|
if (last !== null) s.draw.lastOfferPly[c] = Math.min(last, s.moves.length);
|
|
}
|
|
events.push({ type: 'undoAccepted', color: by, plies });
|
|
} else {
|
|
events.push({ type: 'undoDeclined', color: by });
|
|
}
|
|
break;
|
|
}
|
|
case 'offerDraw':
|
|
s.draw.pendingBy = me;
|
|
s.draw.lastOfferPly[me] = s.moves.length;
|
|
events.push({ type: 'drawOffered', color: me });
|
|
break;
|
|
case 'respondDraw':
|
|
s.draw.pendingBy = null;
|
|
if (a.accept) {
|
|
finish(s, null, 'drawAgreed');
|
|
events.push({ type: 'drawAccepted' });
|
|
events.push({ type: 'gameEnded', winner: null, reason: 'drawAgreed' });
|
|
} else events.push({ type: 'drawDeclined' });
|
|
break;
|
|
case 'cancelOffer':
|
|
if (s.undo.pending?.by === me) s.undo.pending = null;
|
|
if (s.draw.pendingBy === me) s.draw.pendingBy = null;
|
|
events.push({ type: 'offerCancelled', color: me });
|
|
break;
|
|
case 'resign':
|
|
finish(s, other(me), 'resign');
|
|
events.push({ type: 'resigned', color: me });
|
|
events.push({ type: 'gameEnded', winner: other(me), reason: 'resign' });
|
|
break;
|
|
}
|
|
return { state: s, events };
|
|
},
|
|
|
|
view(s, viewer) {
|
|
const myColor = viewer ? colorOf(s, viewer) : null;
|
|
const limit = undoLimit(s.options);
|
|
let lastMove: OthelloView['lastMove'] = null;
|
|
for (let i = s.moves.length - 1; i >= 0; i--) {
|
|
const m = s.moves[i]!;
|
|
if (m.kind === 'place') {
|
|
lastMove = { x: m.x, y: m.y, color: m.color, flipped: m.flipped };
|
|
break;
|
|
}
|
|
}
|
|
const mine = s.phase === 'playing' && myColor !== null && myColor === s.turn;
|
|
return {
|
|
size: SIZE,
|
|
board: s.board,
|
|
players: s.players,
|
|
myColor,
|
|
turn: s.turn,
|
|
phase: s.phase,
|
|
discs: countDiscs(s.board),
|
|
moves: s.moves,
|
|
lastMove,
|
|
moveCount: s.moves.length,
|
|
legalMoves: mine
|
|
? legalMoves(s.board, DISC[myColor]).map((m) => ({ x: m.i % SIZE, y: Math.floor(m.i / SIZE), flips: m.flipped.length, flipped: m.flipped }))
|
|
: null,
|
|
showLegalMoves: s.options.showLegalMoves,
|
|
showFlipCount: s.options.showFlipCount,
|
|
emptyToWinner: s.options.emptyToWinner,
|
|
timeControl: s.options.timeControl,
|
|
remainingMs: s.clock.remainingMs,
|
|
turnStartedAt: s.clock.turnStartedAt,
|
|
undo: {
|
|
allowed: s.options.undo !== 'off',
|
|
remaining: {
|
|
black: Number.isFinite(limit) ? limit - s.undo.usedBy.black : null,
|
|
white: Number.isFinite(limit) ? limit - s.undo.usedBy.white : null,
|
|
},
|
|
pending: s.undo.pending,
|
|
},
|
|
draw: { allowed: s.options.drawOffer, pendingBy: s.draw.pendingBy },
|
|
result: s.result,
|
|
};
|
|
},
|
|
|
|
activePlayers(s) {
|
|
if (s.phase !== 'playing') return [];
|
|
const out = [s.players[s.turn]];
|
|
const responder = pendingResponder(s);
|
|
if (responder && responder !== s.turn) out.push(s.players[responder]);
|
|
return out;
|
|
},
|
|
|
|
deadline(s) {
|
|
if (s.phase !== 'playing') return null;
|
|
const tc = s.options.timeControl;
|
|
const start = s.clock.turnStartedAt;
|
|
if (tc.kind === 'perMove') return start + tc.perMoveSec * 1000;
|
|
if (tc.kind === 'fischer') return start + s.clock.remainingMs[s.turn];
|
|
return null; // 시간 제한 없음: 차례 마감 없음
|
|
},
|
|
|
|
timeoutPlayers(s) {
|
|
return s.phase === 'playing' ? [s.players[s.turn]] : [];
|
|
},
|
|
|
|
onTimeout() {
|
|
return { type: 'timeout' };
|
|
},
|
|
|
|
onLeave() {
|
|
return { type: 'resign' };
|
|
},
|
|
|
|
result(s): GameResult | null {
|
|
if (!s.result) return null;
|
|
const { winner, reason, summary, displayScore } = s.result;
|
|
const ranking = winner ? [[s.players[winner]], [s.players[other(winner)]]] : [[s.players.black, s.players.white]];
|
|
const map: Record<OthelloReason, GameResult['reason']> = {
|
|
noMoves: 'normal',
|
|
resign: 'resign',
|
|
timeLoss: 'timeout',
|
|
drawAgreed: 'draw-agreed',
|
|
};
|
|
return {
|
|
ranking,
|
|
scores: { [s.players.black]: displayScore.black, [s.players.white]: displayScore.white },
|
|
scoreText: { [s.players.black]: `${displayScore.black}점`, [s.players.white]: `${displayScore.white}점` },
|
|
summary,
|
|
reason: map[reason],
|
|
};
|
|
},
|
|
|
|
legalActions(s, p) {
|
|
const me = colorOf(s, p);
|
|
if (!me || s.phase !== 'playing') return [];
|
|
const responder = pendingResponder(s);
|
|
if (responder === me) {
|
|
return s.undo.pending ? [{ type: 'respondUndo', accept: false }] : [{ type: 'respondDraw', accept: false }];
|
|
}
|
|
if (s.turn !== me) return [];
|
|
return legalMoves(s.board, DISC[me]).map((m) => ({ type: 'place' as const, x: m.i % SIZE, y: Math.floor(m.i / SIZE) }));
|
|
},
|
|
};
|