병합: wt2/g4-party
This commit is contained in:
@@ -80,7 +80,7 @@ describe('판 만들기', () => {
|
||||
}
|
||||
const s = make(['A', 'B', 'C']);
|
||||
expect(new Set(Object.values(s.boards))).toEqual(new Set([s.initial]));
|
||||
expect(s.endsAt).toBe(START + 120_000);
|
||||
expect(s.endsAt!).toBe(START + 120_000);
|
||||
expect(make(['A'], { timeLimitSec: 60 }).endsAt).toBe(START + 60_000);
|
||||
});
|
||||
|
||||
@@ -160,10 +160,10 @@ describe('진행', () => {
|
||||
s = act(s, 'A', sel(m1!), START + 1000);
|
||||
s = act(s, 'B', sel(m1!), START + 1000);
|
||||
s = act(s, 'B', sel(findMoves(s.boards.B!)[0]!), START + 2000);
|
||||
expect(apple.deadline!(s)).toBe(s.endsAt);
|
||||
expect(apple.timeoutNotBefore!(s)).toBe(s.endsAt);
|
||||
expect(reason(s, 'C', sel(m1!), s.endsAt)).toBe('시간이 다 됐어요.');
|
||||
s = tick(s, s.endsAt);
|
||||
expect(apple.deadline!(s)).toBe(s.endsAt!);
|
||||
expect(apple.timeoutNotBefore!(s)).toBe(s.endsAt!);
|
||||
expect(reason(s, 'C', sel(m1!), s.endsAt!)).toBe('시간이 다 됐어요.');
|
||||
s = tick(s, s.endsAt!);
|
||||
expect(s.phase).toBe('ended');
|
||||
const r = apple.result(s)!;
|
||||
expect(r.ranking).toEqual([['B'], ['A'], ['C']]);
|
||||
@@ -178,7 +178,7 @@ describe('진행', () => {
|
||||
let s = make(['A']);
|
||||
s = tick(s, START);
|
||||
s = act(s, 'A', sel(findMoves(s.initial)[0]!), START + 500);
|
||||
s = tick(s, s.endsAt + 5);
|
||||
s = tick(s, s.endsAt! + 5);
|
||||
const r = apple.result(s)!;
|
||||
expect(r.ranking).toEqual([['A']]);
|
||||
expect(r.summary).toBe(`시간이 다 됐어요. 사과 ${s.score.A}개를 지웠어요`);
|
||||
@@ -220,7 +220,8 @@ describe('진행', () => {
|
||||
expect(solo.phase).toBe('ended');
|
||||
});
|
||||
|
||||
test('클라이언트 액션 스키마에는 select만(tick/leave는 시스템 전용)', () => {
|
||||
test('클라이언트 액션 스키마에는 select·stop만(tick/leave는 시스템 전용)', () => {
|
||||
expect(apple.actionSchema.safeParse({ type: 'stop' }).success).toBe(true);
|
||||
expect(apple.actionSchema.safeParse({ type: 'tick' }).success).toBe(false);
|
||||
expect(apple.actionSchema.safeParse({ type: 'leave' }).success).toBe(false);
|
||||
expect(apple.actionSchema.safeParse({ type: 'select', r0: 0, c0: 0, r1: 9, c1: 16 }).success).toBe(true);
|
||||
@@ -229,6 +230,47 @@ describe('진행', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('제한 시간 무제한', () => {
|
||||
test('마감 없음: 모두 막히거나 「여기까지」하면 끝, 시간 제한 방에서는 여기까지 거절', () => {
|
||||
let s = make(['A', 'B'], { timeLimitSec: null });
|
||||
expect(s.endsAt).toBeNull();
|
||||
expect(apple.deadline!(s)).toBe(s.countdownEndsAt);
|
||||
expect(reason(s, 'A', { type: 'stop' }, T0 + 100)).toBe('곧 시작해요. 잠시만 기다려 주세요.');
|
||||
s = tick(s, START);
|
||||
expect(s.phase).toBe('playing');
|
||||
expect(s.status.A).toBe('playing'); // the start tick is not an away tick
|
||||
expect(apple.deadline!(s)).toBeNull();
|
||||
expect(apple.timeoutNotBefore!(s)).toBeNull();
|
||||
// Hours later the board still takes moves.
|
||||
const m = findMoves(s.initial)[0]!;
|
||||
s = act(s, 'A', sel(m), START + 3_600_000);
|
||||
expect(s.score.A).toBeGreaterThan(0);
|
||||
s = act(s, 'A', { type: 'stop' }, START + 3_600_100);
|
||||
expect(s.status.A).toBe('done');
|
||||
expect(reason(s, 'A', { type: 'stop' }, START + 3_600_200)).toBe('이미 끝냈어요.');
|
||||
expect(apple.activePlayers(s)).toEqual(['B']);
|
||||
expect(apple.timeoutPlayers!(s)).toEqual(['B']);
|
||||
s = act(s, 'B', { type: 'stop' }, START + 3_600_300);
|
||||
expect(s.phase).toBe('ended');
|
||||
const r = apple.result(s)!;
|
||||
expect(r.ranking).toEqual([['A'], ['B']]);
|
||||
expect(r.summary).toContain('모두 끝냈어요');
|
||||
expect(reason(tick(make(['A']), START), 'A', { type: 'stop' }, START + 10)).toBe('제한 시간이 있는 방에서는 끝날 때까지 해요.');
|
||||
});
|
||||
|
||||
test('자리 비움: 방이 유예 뒤 tick을 보내면 그 사람은 여기까지(점수 유지), 혼자면 바로 끝', () => {
|
||||
let s = tick(make(['A', 'B'], { timeLimitSec: null }), START);
|
||||
s = act(s, 'B', sel(findMoves(s.initial)[0]!), START + 500);
|
||||
s = apple.apply(s, 'B', { type: 'tick' }, { rng: rng(), now: START + 60_000 }).state;
|
||||
expect(s.status.B).toBe('done');
|
||||
expect(s.score.B).toBeGreaterThan(0);
|
||||
expect(s.phase).toBe('playing');
|
||||
const solo = apple.apply(tick(make(['A'], { timeLimitSec: null }), START), 'A', { type: 'tick' }, { rng: rng(), now: START + 60_000 }).state;
|
||||
expect(solo.phase).toBe('ended');
|
||||
expect(apple.result(solo)!.summary).toBe('여기까지 했어요. 사과 0개를 지웠어요');
|
||||
});
|
||||
});
|
||||
|
||||
describe('무작위 대국', () => {
|
||||
test.each([1, 2, 5, 8])('%i명: 엔진 randomPlayout(유출·JSON·결정성) 끝까지', (n) => {
|
||||
const players = Array.from({ length: n }, (_, i) => `p${i + 1}`);
|
||||
@@ -244,4 +286,11 @@ describe('무작위 대국', () => {
|
||||
for (const p of players) expect(s.score[p]).toBe([...s.boards[p]!].filter((c) => c === '0').length);
|
||||
}
|
||||
});
|
||||
test.each([1, 3])('무제한 %i명: 끝까지(여기까지·자리 비움 tick 포함)', (n) => {
|
||||
const players = Array.from({ length: n }, (_, i) => `p${i + 1}`);
|
||||
for (let i = 0; i < playoutSeeds(10); i++) {
|
||||
const a = randomPlayout(apple, { players, options: apple.optionsSchema.parse({ timeLimitSec: null }), seed: seedN(900 + n * 10 + i), maxSteps: 1000, maxApplyMs: 20 });
|
||||
expect(a.finished).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -133,7 +133,7 @@ interface Ctx {
|
||||
events: GameEvent[];
|
||||
}
|
||||
|
||||
const inGame = (s: S, p: PlayerId) => s.status[p] === 'playing' || s.status[p] === 'stuck';
|
||||
const inGame = (s: S, p: PlayerId) => s.status[p] !== 'left';
|
||||
/** The countdown is over (the room timer may not have ticked yet). */
|
||||
const started = (s: S, now: number | undefined) => s.phase === 'playing' || (s.phase === 'countdown' && now !== undefined && now >= s.countdownEndsAt);
|
||||
|
||||
@@ -148,7 +148,15 @@ function catchUp(s: S, ctx: Ctx): void {
|
||||
s.phase = 'playing';
|
||||
ctx.events.push({ type: 'start' });
|
||||
}
|
||||
if (s.phase === 'playing' && ctx.now >= s.endsAt) finish(s, 'time', ctx);
|
||||
if (s.phase === 'playing' && s.endsAt !== null && ctx.now >= s.endsAt) finish(s, 'time', ctx);
|
||||
}
|
||||
|
||||
/** 무제한: a player stops (「여기까지」, or the room timed them out while away); the game ends when nobody is still playing. */
|
||||
function stop(s: S, p: PlayerId, ctx: Ctx): void {
|
||||
if (s.status[p] !== 'playing') return;
|
||||
s.status[p] = 'done';
|
||||
ctx.events.push({ type: 'done', player: p });
|
||||
if (s.order.every((q) => s.status[q] !== 'playing')) finish(s, 'cleared', ctx);
|
||||
}
|
||||
|
||||
function select(s: S, p: PlayerId, a: SelectAction, ctx: Ctx): void {
|
||||
@@ -209,10 +217,15 @@ function finish(s: S, reason: EndReason, ctx: Ctx): void {
|
||||
let summary: string;
|
||||
if (s.order.length === 1) {
|
||||
const n = ranking[0]!.score;
|
||||
summary = reason === 'cleared' ? `더 지울 사과가 없어요. 사과 ${n}개를 지웠어요` : `시간이 다 됐어요. 사과 ${n}개를 지웠어요`;
|
||||
const why = s.status[s.order[0]!] === 'done' ? '여기까지 했어요.' : '더 지울 사과가 없어요.';
|
||||
summary = reason === 'cleared' ? `${why} 사과 ${n}개를 지웠어요` : `시간이 다 됐어요. 사과 ${n}개를 지웠어요`;
|
||||
} else if (reason === 'left') summary = '다른 사람이 모두 나가서 남은 사람이 이겼어요';
|
||||
else {
|
||||
summary = reason === 'cleared' ? '모두 더 지울 사과가 없어요. 가장 많이 지운 사람이 이겼어요' : '시간이 다 됐어요. 사과를 가장 많이 지운 사람이 이겼어요';
|
||||
const anyDone = s.order.some((p) => s.status[p] === 'done');
|
||||
summary =
|
||||
reason === 'cleared'
|
||||
? `${anyDone ? '모두 끝냈어요' : '모두 더 지울 사과가 없어요'}. 가장 많이 지운 사람이 이겼어요`
|
||||
: '시간이 다 됐어요. 사과를 가장 많이 지운 사람이 이겼어요';
|
||||
if (top.length > 1) summary += ` (공동 1등 ${top.length}명)`;
|
||||
}
|
||||
s.final = { endReason: reason, ranking, summary } satisfies AppleFinal;
|
||||
@@ -250,7 +263,7 @@ export const apple: Def = {
|
||||
recent: per0<number[]>(() => []),
|
||||
phase: 'countdown',
|
||||
countdownEndsAt,
|
||||
endsAt: countdownEndsAt + options.timeLimitSec * 1000,
|
||||
endsAt: options.timeLimitSec === null ? null : countdownEndsAt + options.timeLimitSec * 1000,
|
||||
final: null,
|
||||
};
|
||||
},
|
||||
@@ -264,10 +277,14 @@ export const apple: Def = {
|
||||
return ok;
|
||||
case 'leave':
|
||||
return inGame(s, actor) ? ok : fail('이미 게임에서 빠졌어요.');
|
||||
case 'stop':
|
||||
if (s.endsAt !== null) return fail('제한 시간이 있는 방에서는 끝날 때까지 해요.');
|
||||
if (!started(s, now)) return fail('곧 시작해요. 잠시만 기다려 주세요.');
|
||||
return s.status[actor] === 'playing' ? ok : fail('이미 끝냈어요.');
|
||||
case 'select': {
|
||||
if (s.status[actor] === 'left') return fail('게임에서 빠졌어요.');
|
||||
if (!started(s, now)) return fail('곧 시작해요. 잠시만 기다려 주세요.');
|
||||
if (now !== undefined && now >= s.endsAt) return fail('시간이 다 됐어요.');
|
||||
if (now !== undefined && s.endsAt !== null && now >= s.endsAt) return fail('시간이 다 됐어요.');
|
||||
if (s.status[actor] === 'stuck') return fail('더 지울 수 있는 사과가 없어요.');
|
||||
if (!rateOk(s.recent[actor], now)) return fail('조금 천천히 해 주세요.');
|
||||
const { sum, count } = rectSum(s.boards[actor]!, a);
|
||||
@@ -281,10 +298,14 @@ export const apple: Def = {
|
||||
apply(prev, actor, a, { now }) {
|
||||
const s = clone(prev);
|
||||
const ctx: Ctx = { now, events: [] };
|
||||
const wasPlaying = prev.phase === 'playing';
|
||||
catchUp(s, ctx);
|
||||
if (s.phase !== 'ended') {
|
||||
if (a.type === 'leave') leave(s, actor, ctx);
|
||||
else if (a.type === 'select' && s.phase === 'playing') select(s, actor, a, ctx);
|
||||
else if (a.type === 'stop' && s.phase === 'playing') stop(s, actor, ctx);
|
||||
// 무제한: nothing is due during play, so a tick there means the room timed this player out while away.
|
||||
else if (a.type === 'tick' && wasPlaying && s.endsAt === null) stop(s, actor, ctx);
|
||||
}
|
||||
return { state: s, events: ctx.events };
|
||||
},
|
||||
@@ -316,9 +337,13 @@ export const apple: Def = {
|
||||
return s.phase === 'countdown' ? s.countdownEndsAt : s.endsAt;
|
||||
},
|
||||
|
||||
/** Everyone still in drives the clock (a stuck player too: they wait for the end like everybody else). */
|
||||
/**
|
||||
* Everyone still in drives the clock (a stuck player too: they wait for the end like everybody else).
|
||||
* 무제한 after the start: only those still playing (an away one is stopped after the room's grace period).
|
||||
*/
|
||||
timeoutPlayers(s) {
|
||||
if (s.phase === 'ended') return [];
|
||||
if (s.phase === 'playing' && s.endsAt === null) return s.order.filter((p) => s.status[p] === 'playing');
|
||||
return s.order.filter((p) => inGame(s, p));
|
||||
},
|
||||
|
||||
@@ -351,12 +376,13 @@ export const apple: Def = {
|
||||
};
|
||||
},
|
||||
|
||||
/** Test helper: the clock tick and the first few rectangles that add up to 10. */
|
||||
/** Test helper: the clock tick, the first few rectangles that add up to 10 and (무제한) 「여기까지」. */
|
||||
legalActions(s, p) {
|
||||
if (s.phase === 'ended' || !s.order.includes(p)) return [];
|
||||
const out: A[] = [{ type: 'tick' }];
|
||||
if (s.phase === 'playing' && s.status[p] === 'playing') {
|
||||
for (const m of findMoves(s.boards[p]!, 8)) out.push({ type: 'select', ...m });
|
||||
if (s.endsAt === null) out.push({ type: 'stop' });
|
||||
}
|
||||
return out.filter((x) => apple.validate(s, p, x).ok);
|
||||
},
|
||||
|
||||
@@ -8,29 +8,33 @@ export const COLS = 17;
|
||||
export const CELLS = ROWS * COLS;
|
||||
export const TARGET = 10;
|
||||
|
||||
const lit = <T extends number>(...vals: T[]) =>
|
||||
const lit = <T extends number | null>(...vals: T[]) =>
|
||||
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
||||
|
||||
export const appleOptionsSchema = z.object({
|
||||
timeLimitSec: lit<60 | 120 | 180>(60, 120, 180)
|
||||
/** null = 무제한: everyone plays until they run out of moves or press 「여기까지」 (`stop`). */
|
||||
timeLimitSec: lit<60 | 120 | 180 | null>(60, 120, 180, null)
|
||||
.default(120)
|
||||
.meta({ title: '제한 시간', labels: { 60: '1분', 120: '2분', 180: '3분' } }),
|
||||
.meta({ title: '제한 시간', labels: { 60: '1분', 120: '2분', 180: '3분', null: '무제한(모두 끝낼 때까지)' } }),
|
||||
});
|
||||
export type AppleOptions = z.infer<typeof appleOptionsSchema>;
|
||||
|
||||
/** A rectangle by two opposite corners (any order), rows 0..9, columns 0..16. */
|
||||
export const appleActionSchema = z.object({
|
||||
const selectSchema = z.object({
|
||||
type: z.literal('select'),
|
||||
r0: z.number().int().min(0).max(ROWS - 1),
|
||||
c0: z.number().int().min(0).max(COLS - 1),
|
||||
r1: z.number().int().min(0).max(ROWS - 1),
|
||||
c1: z.number().int().min(0).max(COLS - 1),
|
||||
});
|
||||
export type SelectAction = z.infer<typeof appleActionSchema>;
|
||||
/** Client action plus system-only ones (server timer, leaving) that are not in the schema. */
|
||||
export type AppleAction = SelectAction | { type: 'tick' } | { type: 'leave' };
|
||||
/** `stop` = 「여기까지」: only with no time limit, ends my game with the score I have. */
|
||||
export const appleActionSchema = z.discriminatedUnion('type', [selectSchema, z.object({ type: z.literal('stop') })]);
|
||||
export type SelectAction = z.infer<typeof selectSchema>;
|
||||
/** Client actions plus system-only ones (server timer, leaving) that are not in the schema. */
|
||||
export type AppleAction = z.infer<typeof appleActionSchema> | { type: 'tick' } | { type: 'leave' };
|
||||
|
||||
export type SeatStatus = 'playing' | 'stuck' | 'left';
|
||||
/** `done` = stopped by choice (무제한 「여기까지」) or away past the grace period in a game without a time limit. */
|
||||
export type SeatStatus = 'playing' | 'stuck' | 'done' | 'left';
|
||||
export type EndReason = 'time' | 'cleared' | 'left';
|
||||
|
||||
export interface RankRow {
|
||||
@@ -61,7 +65,8 @@ export interface AppleState {
|
||||
recent: Record<PlayerId, number[]>;
|
||||
phase: 'countdown' | 'playing' | 'ended';
|
||||
countdownEndsAt: number;
|
||||
endsAt: number;
|
||||
/** null = 무제한. */
|
||||
endsAt: number | null;
|
||||
final: AppleFinal | null;
|
||||
}
|
||||
|
||||
@@ -81,7 +86,7 @@ export interface AppleView {
|
||||
/** My board (CELLS digits, '0' = cleared); null for spectators and during the countdown. */
|
||||
cells: string | null;
|
||||
countdownEndsAt: number;
|
||||
endsAt: number;
|
||||
endsAt: number | null;
|
||||
seats: SeatView[];
|
||||
result: AppleFinal | null;
|
||||
}
|
||||
|
||||
@@ -202,7 +202,7 @@ describe('점수(§6)', () => {
|
||||
test('multi: 아무도 못 맞히면 출제자 0점, 시간 만료로 공개', () => {
|
||||
let s = drawWith(make(3), '기린');
|
||||
const d = s.turn.drawer;
|
||||
s = act(s, d, { type: 'tick' }, s.turn.endsAt);
|
||||
s = act(s, d, { type: 'tick' }, s.turn.endsAt!);
|
||||
expect(s.turn.phase).toBe('reveal');
|
||||
expect(s.turn.endReason).toBe('time');
|
||||
expect(s.scores[d]).toBe(0);
|
||||
@@ -224,11 +224,42 @@ describe('점수(§6)', () => {
|
||||
test('speedBonus: 남은 시간 비율 × 5점 추가', () => {
|
||||
let s = drawWith(make(3, { speedBonus: true }), '기린', T0);
|
||||
const g = guessers(s)[0]!;
|
||||
const dur = s.turn.endsAt - s.turn.startedAt;
|
||||
const dur = s.turn.endsAt! - s.turn.startedAt;
|
||||
s = act(s, g, guess('기린'), T0 + dur / 2);
|
||||
expect(s.scores[g]).toBe(10 + 3); // round(2.5)
|
||||
});
|
||||
|
||||
test('그리기 무제한: 마감 없음(힌트는 80초 기준), 출제자 정답 공개로 넘기기, 시간 제한 방에서는 거절', () => {
|
||||
let s = drawWith(make(3, { drawSeconds: null, speedBonus: true }), '아이스크림', T0);
|
||||
const d = s.turn.drawer;
|
||||
const [a, b] = guessers(s) as [string, string];
|
||||
expect(s.turn.endsAt).toBeNull();
|
||||
expect(view(s, a).phaseMs).toBeNull();
|
||||
// Hints still come, at 40 s and 60 s (the 80 s reference); after them nothing is due.
|
||||
expect(cm.deadline!(s)).toBe(T0 + 40_000);
|
||||
s = act(s, d, { type: 'tick' }, T0 + 40_000);
|
||||
expect(s.turn.hintStage).toBe(1);
|
||||
s = act(s, d, { type: 'tick' }, T0 + 60_000);
|
||||
expect(s.turn.hintStage).toBe(2);
|
||||
expect(cm.deadline!(s)).toBeNull();
|
||||
// A guess long after "80 s" is still taken (speed bonus 0 by then).
|
||||
s = act(s, a, guess('아이스크림'), T0 + 600_000);
|
||||
expect(s.scores[a]).toBe(10);
|
||||
expect(reason(s, a, { type: 'giveUp' })).toBe('출제자만 정답을 공개할 수 있어요.');
|
||||
s = act(s, d, { type: 'giveUp' }, T0 + 601_000);
|
||||
expect(s.turn.phase).toBe('reveal');
|
||||
expect(s.turn.endReason).toBe('giveUp');
|
||||
expect(s.scores[d]).toBe(2); // one solver in multi mode
|
||||
expect(view(s, b).word).toBe('아이스크림');
|
||||
const timed = drawWith(make(3), '기린');
|
||||
expect(reason(timed, timed.turn.drawer, { type: 'giveUp' })).toBe('제한 시간이 있는 방에서는 시간이 끝날 때까지 그려요.');
|
||||
// An away drawer is still timed out by the room (nothing else due → drawerAway).
|
||||
let w = drawWith(make(3, { drawSeconds: null, hints: 'basic' }), '기린', T0);
|
||||
expect(cm.deadline!(w)).toBeNull();
|
||||
w = act(w, w.turn.drawer, { type: 'tick' }, T0 + 30_000);
|
||||
expect(w.turn.endReason).toBe('drawerAway');
|
||||
});
|
||||
|
||||
test('신고 과반 → 즉시 종료, 출제자 0점(맞힌 사람 점수 유지)', () => {
|
||||
let s = drawWith(make(5), '기린');
|
||||
const d = s.turn.drawer;
|
||||
@@ -367,16 +398,16 @@ describe('진행(§5.1, §5.2, §8.5)', () => {
|
||||
expect(s.turn.phase).toBe('drawing');
|
||||
expect(s.turn.word!.word).toBe(c0);
|
||||
expect(s.away).toEqual([]);
|
||||
s = act(s, first, { type: 'tick' }, s.turn.endsAt);
|
||||
s = act(s, first, { type: 'tick' }, s.turn.endsAt!);
|
||||
expect(s.turn.phase).toBe('reveal');
|
||||
expect(cm.deadline!(s)).toBe(s.turn.startedAt + REVEAL_MS);
|
||||
s = act(s, first, { type: 'tick' }, s.turn.endsAt);
|
||||
s = act(s, first, { type: 'tick' }, s.turn.endsAt!);
|
||||
expect(s.turn.drawer).not.toBe(first);
|
||||
expect(s.turn.no).toBe(2);
|
||||
const second = s.turn.drawer;
|
||||
s = act(s, second, { type: 'chooseWord', index: 2 }, s.turn.startedAt + 1000);
|
||||
s = act(s, second, { type: 'tick' }, s.turn.endsAt);
|
||||
s = act(s, second, { type: 'tick' }, s.turn.endsAt);
|
||||
s = act(s, second, { type: 'tick' }, s.turn.endsAt!);
|
||||
s = act(s, second, { type: 'tick' }, s.turn.endsAt!);
|
||||
expect(s.finished).toBe(true);
|
||||
const r = cm.result(s)!;
|
||||
expect(r.ranking.flat().sort()).toEqual(['p1', 'p2']);
|
||||
@@ -410,15 +441,15 @@ describe('진행(§5.1, §5.2, §8.5)', () => {
|
||||
// Skipped while away: the next drawers are the others.
|
||||
const seen: string[] = [];
|
||||
for (let i = 0; i < 2; i++) {
|
||||
s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt);
|
||||
s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt!);
|
||||
seen.push(s.turn.drawer);
|
||||
s = act(s, s.turn.drawer, { type: 'chooseWord', index: 0 }, s.turn.startedAt + 100);
|
||||
s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt);
|
||||
s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt!);
|
||||
}
|
||||
expect(seen).not.toContain(d);
|
||||
// "돌아왔어요" clears the mark.
|
||||
expect(reason(s, d, { type: 'back' })).toBeNull();
|
||||
s = act(s, d, { type: 'back' }, s.turn.endsAt - 1);
|
||||
s = act(s, d, { type: 'back' }, s.turn.endsAt! - 1);
|
||||
expect(s.away).toEqual([]);
|
||||
expect(reason(s, d, { type: 'back' })).not.toBeNull();
|
||||
});
|
||||
@@ -431,7 +462,7 @@ describe('진행(§5.1, §5.2, §8.5)', () => {
|
||||
expect(s.turn.phase).toBe('reveal');
|
||||
expect(s.turn.endReason).toBe('drawerLeft');
|
||||
expect(cm.onLeave!(s, d)).toBeNull();
|
||||
s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt);
|
||||
s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt!);
|
||||
expect(s.turn.drawer).not.toBe(d);
|
||||
const other = s.order.find((p) => p !== d && p !== s.turn.drawer)!;
|
||||
s = act(s, other, { type: 'leave' }, s.turn.startedAt + 100);
|
||||
@@ -454,7 +485,7 @@ describe('진행(§5.1, §5.2, §8.5)', () => {
|
||||
let s = drawWith(make(4, { guessMode: 'firstOnly', answererDraws: true }), '기린');
|
||||
const g = guessers(s)[2]!;
|
||||
s = act(s, g, guess('기린'), T0 + 2000);
|
||||
s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt);
|
||||
s = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt!);
|
||||
expect(s.turn.drawer).toBe(g);
|
||||
});
|
||||
|
||||
@@ -466,7 +497,7 @@ describe('진행(§5.1, §5.2, §8.5)', () => {
|
||||
s.turnsPlayed = s.totalTurns - 1;
|
||||
s.round = s.options.rounds;
|
||||
s.turn.drawer = s.order.at(-1)!;
|
||||
const r = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt);
|
||||
const r = act(s, s.turn.drawer, { type: 'tick' }, s.turn.endsAt!);
|
||||
expect(r.finished).toBe(true);
|
||||
expect(cm.result(r)!.ranking.map((g) => [...g].sort())).toEqual([['p2'], ['p1', 'p3'], ['p4']]);
|
||||
expect(r.final!.ranking.map((x) => x.rank)).toEqual([1, 2, 2, 4]);
|
||||
@@ -540,7 +571,8 @@ function fastPlayout(players: PlayerId[], options: CatchmindOptions, seed: RngSt
|
||||
invariants(s, poolSize);
|
||||
if (cm.result(s)) return { state: s, trace, steps: step };
|
||||
// Timer: the drawer's tick when due (as the room would), otherwise a random actor.
|
||||
const due = cm.deadline!(s)!;
|
||||
// 무제한 drawing without hints has no deadline: only the random "away drawer" ticks below.
|
||||
const due = cm.deadline!(s) ?? Infinity;
|
||||
let p: PlayerId;
|
||||
let a: CatchmindAction;
|
||||
if (now >= due || pick.int(12) === 0) {
|
||||
@@ -603,7 +635,7 @@ describe('무작위 대국(§10, docs/09 §7)', () => {
|
||||
const options = opts({
|
||||
guessMode: pk.int(3) === 0 ? 'firstOnly' : 'multi',
|
||||
rounds: (1 + pk.int(3)) as 1 | 2 | 3,
|
||||
drawSeconds: ([60, 80, 100, 120] as const)[pk.int(4)]!,
|
||||
drawSeconds: ([60, 80, 100, 120, null] as const)[pk.int(5)]!,
|
||||
wordChoice: pk.int(4) !== 0,
|
||||
hints: (['none', 'basic', 'full'] as const)[pk.int(3)]!,
|
||||
letterReport: pk.int(3) !== 0,
|
||||
|
||||
@@ -118,11 +118,16 @@ export function reportsNeeded(s: S): number {
|
||||
return Math.floor(voters / 2) + 1;
|
||||
}
|
||||
|
||||
/** 무제한 drawings time their hints and the speed bonus as if they had the default 80 seconds. */
|
||||
export const UNLIMITED_REF_MS = 80_000;
|
||||
/** The drawing's length for hints / speed bonus (무제한: the 80 s reference). */
|
||||
const drawLen = (t: Turn) => (t.endsAt === null ? UNLIMITED_REF_MS : t.endsAt - t.startedAt);
|
||||
|
||||
/** Next hint time while drawing (`hints: full` only): 50% → initials, 75% → one letter (skipped for ≤ 2 letters). */
|
||||
export function nextHintAt(s: S): number | null {
|
||||
const t = s.turn;
|
||||
if (s.finished || t.phase !== 'drawing' || s.options.hints !== 'full' || !t.word) return null;
|
||||
const dur = t.endsAt - t.startedAt;
|
||||
const dur = drawLen(t);
|
||||
if (t.hintStage === 0) return t.startedAt + Math.round(dur * 0.5);
|
||||
if (t.hintStage === 1 && letters(t.word.word) > 2) return t.startedAt + Math.round(dur * 0.75);
|
||||
return null;
|
||||
@@ -178,7 +183,7 @@ function beginDrawing(s: S, index: number, ctx: Ctx): void {
|
||||
t.choices = [];
|
||||
t.phase = 'drawing';
|
||||
t.startedAt = ctx.now;
|
||||
t.endsAt = ctx.now + s.options.drawSeconds * 1000;
|
||||
t.endsAt = s.options.drawSeconds === null ? null : ctx.now + s.options.drawSeconds * 1000;
|
||||
t.hintStage = 0;
|
||||
ctx.events.push({ type: 'drawing', no: t.no, drawer: t.drawer });
|
||||
}
|
||||
@@ -297,7 +302,7 @@ function guess(s: S, p: PlayerId, raw: string, ctx: Ctx): void {
|
||||
if (j === 'correct') {
|
||||
const k = t.solvers.length + 1;
|
||||
let points = s.options.guessMode === 'multi' ? Math.max(10 - 2 * (k - 1), 4) : 10;
|
||||
if (s.options.speedBonus) points += Math.round((5 * Math.max(0, t.endsAt - ctx.now)) / Math.max(1, t.endsAt - t.startedAt));
|
||||
if (s.options.speedBonus) points += Math.round((5 * Math.max(0, t.startedAt + drawLen(t) - ctx.now)) / Math.max(1, drawLen(t)));
|
||||
t.solvers.push({ id: p, at: ctx.now, points });
|
||||
s.scores[p] = (s.scores[p] ?? 0) + points;
|
||||
s.correctCounts[p] = (s.correctCounts[p] ?? 0) + 1;
|
||||
@@ -318,7 +323,7 @@ function tick(s: S, ctx: Ctx): void {
|
||||
const t = s.turn;
|
||||
if (t.phase === 'choosing') {
|
||||
// Only a disconnected drawer is timed out before the 10 s are up (room grace hook): skip them next time.
|
||||
if (ctx.now < t.endsAt) markAway(s, t.drawer);
|
||||
if (ctx.now < t.endsAt!) markAway(s, t.drawer);
|
||||
beginDrawing(s, 0, ctx);
|
||||
return;
|
||||
}
|
||||
@@ -328,7 +333,7 @@ function tick(s: S, ctx: Ctx): void {
|
||||
advanceHint(s, ctx);
|
||||
hinted = true;
|
||||
}
|
||||
if (ctx.now >= t.endsAt) return endDrawing(s, 'time', ctx);
|
||||
if (t.endsAt !== null && ctx.now >= t.endsAt) return endDrawing(s, 'time', ctx);
|
||||
if (hinted) return;
|
||||
// Nothing was due: the drawer has been disconnected for DRAWER_AWAY_MS (§5.2) → 0 points, answer revealed.
|
||||
markAway(s, t.drawer);
|
||||
@@ -499,7 +504,7 @@ function buildView(s: S, viewer: PlayerId | null, withCanvas: boolean): Catchmin
|
||||
drawer: t.drawer,
|
||||
startedAt: t.startedAt,
|
||||
endsAt: t.endsAt,
|
||||
phaseMs: t.endsAt - t.startedAt,
|
||||
phaseMs: t.endsAt === null ? null : t.endsAt - t.startedAt,
|
||||
choices: isDrawer && t.phase === 'choosing' && !s.finished ? t.choices.map((w) => ({ word: w.word, category: w.category, difficulty: w.difficulty })) : null,
|
||||
word: knows && t.word ? t.word.word : null,
|
||||
category: knows && t.word ? t.word.category : null,
|
||||
@@ -613,7 +618,7 @@ export const catchmind: GameDefinition<S, A, CatchmindView, CatchmindOptions> =
|
||||
const len = [...cleanText(a.text)].length;
|
||||
if (len < 1) return fail('내용을 입력해 주세요.');
|
||||
if (len > GUESS_MAX) return fail(`${GUESS_MAX}자까지 쓸 수 있어요.`);
|
||||
if (now !== undefined && now >= t.endsAt) return fail('시간이 다 됐어요.');
|
||||
if (now !== undefined && t.endsAt !== null && now >= t.endsAt) return fail('시간이 다 됐어요.');
|
||||
if (!rateOk(s.msgTimes[actor], GUESS_MSGS_PER_SEC, now)) return fail('조금 천천히 보내 주세요.');
|
||||
return ok;
|
||||
}
|
||||
@@ -632,6 +637,11 @@ export const catchmind: GameDefinition<S, A, CatchmindView, CatchmindOptions> =
|
||||
return ok;
|
||||
case 'back':
|
||||
return s.away.includes(actor) ? ok : fail('이미 게임에 참여하고 있어요.');
|
||||
case 'giveUp':
|
||||
if (actor !== t.drawer) return fail('출제자만 정답을 공개할 수 있어요.');
|
||||
if (t.phase !== 'drawing') return fail('그리는 동안에만 정답을 공개할 수 있어요.');
|
||||
if (s.options.drawSeconds !== null) return fail('제한 시간이 있는 방에서는 시간이 끝날 때까지 그려요.');
|
||||
return ok;
|
||||
case 'report':
|
||||
if (!s.options.letterReport) return fail('이 방은 신고를 쓰지 않아요.');
|
||||
if (t.phase !== 'drawing') return fail('그리는 동안에만 신고할 수 있어요.');
|
||||
@@ -670,6 +680,9 @@ export const catchmind: GameDefinition<S, A, CatchmindView, CatchmindOptions> =
|
||||
case 'back':
|
||||
ctx.events.push({ type: 'back', player: actor });
|
||||
break;
|
||||
case 'giveUp':
|
||||
endDrawing(s, 'giveUp', ctx);
|
||||
break;
|
||||
case 'report':
|
||||
s.turn.reports.push(actor);
|
||||
ctx.events.push({ type: 'report', count: s.turn.reports.length, need: reportsNeeded(s) });
|
||||
@@ -702,7 +715,9 @@ export const catchmind: GameDefinition<S, A, CatchmindView, CatchmindOptions> =
|
||||
deadline(s) {
|
||||
if (s.finished) return null;
|
||||
const h = nextHintAt(s);
|
||||
return h === null ? s.turn.endsAt : Math.min(h, s.turn.endsAt);
|
||||
const e = s.turn.endsAt;
|
||||
if (h === null) return e;
|
||||
return e === null ? h : Math.min(h, e);
|
||||
},
|
||||
|
||||
/** The drawer's clock drives every server tick (choosing, hints, time up, reveal). */
|
||||
@@ -768,7 +783,7 @@ export const catchmind: GameDefinition<S, A, CatchmindView, CatchmindOptions> =
|
||||
out.push({ type: 'draw', op: { k: 'e', s: t.lastStroke } });
|
||||
}
|
||||
if (t.live > 0) out.push({ type: 'draw', op: { k: 'u' } }, { type: 'draw', op: { k: 'x' } });
|
||||
out.push({ type: 'reaction', code: 'almost' });
|
||||
out.push({ type: 'reaction', code: 'almost' }, { type: 'giveUp' });
|
||||
} else {
|
||||
out.push({ type: 'guess', text: t.word!.word }, { type: 'guess', text: '모르겠어요' }, { type: 'guess', text: `${t.word!.word} 맞나` }, { type: 'report' });
|
||||
}
|
||||
|
||||
@@ -53,9 +53,10 @@ export const catchmindOptionsSchema = z.object({
|
||||
rounds: lit<1 | 2 | 3>(1, 2, 3)
|
||||
.default(2)
|
||||
.meta({ title: '라운드 수(모두 한 번씩 그리면 1라운드)', labels: { 1: '1라운드', 2: '2라운드', 3: '3라운드' } }),
|
||||
drawSeconds: lit<60 | 80 | 100 | 120>(60, 80, 100, 120)
|
||||
/** null = 무제한: the drawing goes on until it is solved (or the drawer opens the answer with `giveUp`). */
|
||||
drawSeconds: lit<60 | 80 | 100 | 120 | null>(60, 80, 100, 120, null)
|
||||
.default(80)
|
||||
.meta({ title: '그리기 제한 시간', labels: { 60: '60초', 80: '80초', 100: '100초', 120: '120초' } }),
|
||||
.meta({ title: '그리기 제한 시간', labels: { 60: '60초', 80: '80초', 100: '100초', 120: '120초', null: '무제한(맞히거나 출제자가 넘길 때까지)' } }),
|
||||
wordChoice: z.boolean().default(true).meta({ title: '출제자가 단어 3개 중 고르기(끄면 무작위 1개)' }),
|
||||
categories: z
|
||||
.object(Object.fromEntries(CATEGORIES.map((c) => [c, z.boolean().default(true).meta({ title: CATEGORY_KO[c] })])) as Record<Category, z.ZodDefault<z.ZodBoolean>>)
|
||||
@@ -104,6 +105,8 @@ export const catchmindActionSchema = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('report') }),
|
||||
/** "돌아왔어요": clears the away mark (players marked away are skipped as drawer). */
|
||||
z.object({ type: z.literal('back') }),
|
||||
/** 무제한 only: the drawer opens the answer and ends the drawing (drawer points as usual for those who got it). */
|
||||
z.object({ type: z.literal('giveUp') }),
|
||||
]);
|
||||
/** Client actions plus system-only ones (server timer, leaving) that are not in the schema. */
|
||||
export type CatchmindAction = z.infer<typeof catchmindActionSchema> | { type: 'tick' } | { type: 'leave' };
|
||||
@@ -130,7 +133,7 @@ export interface Solver {
|
||||
points: number;
|
||||
}
|
||||
|
||||
export type TurnEndReason = 'time' | 'allSolved' | 'first' | 'report' | 'drawerAway' | 'drawerLeft';
|
||||
export type TurnEndReason = 'time' | 'allSolved' | 'first' | 'report' | 'drawerAway' | 'drawerLeft' | 'giveUp';
|
||||
|
||||
export interface Turn {
|
||||
/** 1-based turn counter (also the canvas key). */
|
||||
@@ -140,7 +143,8 @@ export interface Turn {
|
||||
choices: WordEntry[];
|
||||
word: WordEntry | null;
|
||||
startedAt: number;
|
||||
endsAt: number;
|
||||
/** null only while drawing with no time limit (무제한). */
|
||||
endsAt: number | null;
|
||||
/** 0 letter count, 1 initial consonants, 2 one letter (§5.4). */
|
||||
hintStage: 0 | 1 | 2;
|
||||
revealIndex: number | null;
|
||||
@@ -243,9 +247,9 @@ export interface CatchmindView {
|
||||
phase: Turn['phase'] | 'ended';
|
||||
drawer: PlayerId;
|
||||
startedAt: number;
|
||||
endsAt: number;
|
||||
/** Length of the current phase (ms), for timer rings. */
|
||||
phaseMs: number;
|
||||
endsAt: number | null;
|
||||
/** Length of the current phase (ms), for timer rings; null = 무제한. */
|
||||
phaseMs: number | null;
|
||||
/** Drawer only, while choosing. */
|
||||
choices: ChoiceView[] | null;
|
||||
/** Drawer, solvers and (after the turn) everyone. */
|
||||
|
||||
@@ -314,6 +314,29 @@ describe('timer and leaving', () => {
|
||||
expect(u.deadlineAt).toBe(clock + 10_000);
|
||||
});
|
||||
|
||||
test('turnSeconds 무제한: no clock on turns or refuting; an away player (room grace) is still moved on and then gets the short clock', () => {
|
||||
let s = rigged(hands, undefined, { turnSeconds: null });
|
||||
// setup's own deadline was computed before rigging; a fresh turn shows the unlimited clock.
|
||||
s = go(s, 'A', { type: 'timeout' });
|
||||
expect(s.current).toBe('B');
|
||||
expect(s.deadlineAt).toBeNull();
|
||||
expect(clue.deadline!(s)).toBeNull();
|
||||
let r = inRoom(rigged(hands, undefined, { turnSeconds: null }), 'A', 'library');
|
||||
r = go(r, 'A', { type: 'suggest', suspect: 'mustard', weapon: 'rope' });
|
||||
expect(r.phase.kind).toBe('refute');
|
||||
expect(r.deadlineAt).toBeNull();
|
||||
let u = rigged(hands, undefined, { turnSeconds: null });
|
||||
u.out.C = true;
|
||||
for (let i = 0; i < 3; i++) {
|
||||
u = go(u, 'A', { type: 'timeout' });
|
||||
u = go(u, 'B', { type: 'roll' });
|
||||
u = go(u, 'B', clue.legalActions!(u, 'B').find((a) => a.type === 'walk' || a.type === 'go')!);
|
||||
if (u.phase.kind === 'suggest') u = go(u, 'B', { type: 'end' });
|
||||
}
|
||||
expect(u.current).toBe('A');
|
||||
expect(u.deadlineAt).toBe(clock + 10_000);
|
||||
});
|
||||
|
||||
test('leaving: cards go face up, the answer chain and turns go on, the last one in the room wins', () => {
|
||||
let s = inRoom(rigged(hands), 'A', 'library');
|
||||
s = go(s, 'A', { type: 'suggest', suspect: 'green', weapon: 'rope' });
|
||||
@@ -407,7 +430,12 @@ describe('random games', () => {
|
||||
test('engine random playouts (secretsOf leak check, JSON round trip)', () => {
|
||||
for (let i = 0; i < playoutSeeds(60); i++) {
|
||||
const n = 3 + (i % 4);
|
||||
const r = randomPlayout(clue, { players: ['A', 'B', 'C', 'D', 'E', 'F'].slice(0, n), seed: seedN(i + 1), maxApplyMs: 50 });
|
||||
const r = randomPlayout(clue, {
|
||||
players: ['A', 'B', 'C', 'D', 'E', 'F'].slice(0, n),
|
||||
seed: seedN(i + 1),
|
||||
maxApplyMs: 50,
|
||||
...(i % 4 === 3 ? { options: clue.optionsSchema.parse({ turnSeconds: null }) } : {}),
|
||||
});
|
||||
expect(r.finished).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -66,11 +66,14 @@ function refreshDeadline(s: ClueState, now: number): void {
|
||||
s.deadlineAt = null;
|
||||
return;
|
||||
}
|
||||
const unlimited = s.options.turnSeconds === null;
|
||||
if (s.phase.kind === 'refute') {
|
||||
s.deadlineAt = now + REFUTE_MS;
|
||||
s.deadlineAt = unlimited ? null : now + REFUTE_MS;
|
||||
return;
|
||||
}
|
||||
s.deadlineAt = now + ((s.idle[s.current] ?? 0) >= IDLE_TURNS ? IDLE_MS : s.options.turnSeconds * 1000);
|
||||
// Someone who let the clock run out three turns in a row gets a short clock (무제한 too: only away players time out there).
|
||||
if ((s.idle[s.current] ?? 0) >= IDLE_TURNS) s.deadlineAt = now + IDLE_MS;
|
||||
else s.deadlineAt = unlimited ? null : now + s.options.turnSeconds! * 1000;
|
||||
}
|
||||
|
||||
function finish(s: ClueState, winner: PlayerId | null, reason: ClueFinal['reason'], events: GameEvent[]): void {
|
||||
|
||||
@@ -7,7 +7,7 @@ export * from './board';
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
const lit = <T extends string | number>(...vals: T[]) =>
|
||||
const lit = <T extends string | number | null>(...vals: T[]) =>
|
||||
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
||||
|
||||
export const clueOptionsSchema = z.object({
|
||||
@@ -15,9 +15,10 @@ export const clueOptionsSchema = z.object({
|
||||
.enum(['dice', 'free'])
|
||||
.default('dice')
|
||||
.meta({ title: '이동 방식', labels: { dice: '주사위 2개로 복도 이동(원작처럼)', free: '빠르게(아무 방이나 바로 이동)' } }),
|
||||
turnSeconds: lit(30, 45, 60, 90)
|
||||
/** null = 무제한: no clock on turns or on showing a card (only players away past the room's grace period are moved on). */
|
||||
turnSeconds: lit<30 | 45 | 60 | 90 | null>(30, 45, 60, 90, null)
|
||||
.default(60)
|
||||
.meta({ title: '차례 제한 시간', labels: { 30: '30초', 45: '45초', 60: '60초', 90: '90초' } }),
|
||||
.meta({ title: '차례 제한 시간', labels: { 30: '30초', 45: '45초', 60: '60초', 90: '90초', null: '무제한' } }),
|
||||
});
|
||||
export type ClueOptions = z.infer<typeof clueOptionsSchema>;
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
allCardIds,
|
||||
cardOf,
|
||||
fiveFruit,
|
||||
flipMs,
|
||||
halliGalli as hg,
|
||||
type Fruit,
|
||||
type HalliGalliAction,
|
||||
@@ -94,7 +95,8 @@ function rig(
|
||||
s.phase = 'playing';
|
||||
s.turn = r.turn ?? players[0]!;
|
||||
s.turnStartedAt = now;
|
||||
s.turnDeadline = now + s.options.flipSeconds * 1000 * (s.options.kidMode ? 8 / s.options.flipSeconds : 1);
|
||||
const ms = flipMs(s.options);
|
||||
s.turnDeadline = ms === null ? null : now + ms;
|
||||
s.flipAllowedAt = now;
|
||||
s.pendingFlip = null;
|
||||
s.tableVersion = 5;
|
||||
@@ -388,11 +390,35 @@ describe('뒤집기와 시간 (§5.1, §8.5)', () => {
|
||||
expect(n.turnDeadline).toBe(START + 4000);
|
||||
});
|
||||
|
||||
test('뒤집기 시간 무제한: 기다리다가 직접 뒤집기, 끊기면 방의 유예 뒤 자동, 자동 뒤집기는 3초 간격', () => {
|
||||
const s = rig(['A', 'B'], { decks: { A: [3, 3], B: [3, 3] }, turn: 'A' }, { flipSeconds: null, timeLimitMin: null });
|
||||
expect(s.turnDeadline).toBeNull();
|
||||
expect(hg.deadline!(s)).toBeNull();
|
||||
expect(hg.view(s, 'A').flipTotalMs).toBeNull();
|
||||
// A non-turn tick (someone else's clock) does nothing however late it is.
|
||||
const idle = act(s, 'B', { type: 'tick' }, START + 600_000);
|
||||
expect(idle.faceUp.A).toHaveLength(0);
|
||||
// A flips when ready; B's turn also has no deadline.
|
||||
const n = act(s, 'A', { type: 'flip' }, START + 60_000);
|
||||
expect(n.faceUp.A).toHaveLength(1);
|
||||
expect(n.turn).toBe('B');
|
||||
expect(n.turnDeadline).toBeNull();
|
||||
expect(hg.deadline!(n)).toBeNull();
|
||||
// The room times out an away turn player (its own grace period): that still flips.
|
||||
const away = act(n, 'B', { type: 'tick' }, START + 120_000);
|
||||
expect(away.faceUp.B).toHaveLength(1);
|
||||
// 무제한 + 자동 뒤집기 keeps a 3-second pace (어린이 모드 8초).
|
||||
const auto = rig(['A', 'B'], { decks: { A: [3], B: [3] }, turn: 'A' }, { flipSeconds: null, autoFlip: true });
|
||||
expect(auto.turnDeadline).toBe(START + 3000);
|
||||
expect(flipMs({ ...auto.options, kidMode: true })).toBe(8000);
|
||||
expect(flipMs({ ...s.options, kidMode: true })).toBeNull();
|
||||
});
|
||||
|
||||
test('시간 제한 만료: 보유 카드(덱 + 자기 공개 더미) 순, 동점은 정답 횟수, 그래도 같으면 공동', () => {
|
||||
const s = rig(['A', 'B', 'C', 'D'], { decks: { A: [3], B: [5], C: [4], D: [4] }, faceUp: { A: ['S1', 'S1'], C: ['P1'], D: ['P1'] }, turn: 'A' }, { timeLimitMin: 5 });
|
||||
s.correctCount = { A: 0, B: 0, C: 2, D: 2 };
|
||||
// A 5 (3 + 2), B 5, C 5, D 5 → A,B (0 correct) below C,D (2 correct)
|
||||
expect(hg.deadline!(s)).toBe(Math.min(s.endsAt!, s.turnDeadline));
|
||||
expect(hg.deadline!(s)).toBe(Math.min(s.endsAt!, s.turnDeadline!));
|
||||
const n = act(s, 'B', ringA(s), s.endsAt!); // any action at/after the end time ends the game first
|
||||
expect(n.phase).toBe('ended');
|
||||
expect(n.final!.endReason).toBe('timeLimit');
|
||||
@@ -657,6 +683,8 @@ const PRESETS: Partial<HalliGalliOptions>[] = [
|
||||
{ penaltyEscalation: true, strikeOut: true, timeLimitMin: 5 },
|
||||
{ wrongToPot: true, autoFlip: true, flipGuardMs: 400, wrongRingLockoutMs: 0 },
|
||||
{ duelWrongLoses: true, kidMode: true, timeLimitMin: 15 },
|
||||
{ flipSeconds: null, kidMode: true },
|
||||
{ flipSeconds: null, autoFlip: true, timeLimitMin: null },
|
||||
];
|
||||
|
||||
describe('random playouts (§10, docs/09 §7)', () => {
|
||||
|
||||
@@ -34,7 +34,15 @@ export const AWAY_FLIP_MS = 1000;
|
||||
const LOG_KEEP = 30;
|
||||
const POINTS = [3, 2, 1];
|
||||
|
||||
export const flipMs = (o: HalliGalliOptions): number => (o.kidMode ? 8 : o.flipSeconds) * 1000;
|
||||
/** Flip time limit in ms; null = 무제한 (자동 뒤집기 still needs a pace: 3 s, 어린이 모드 8 s). */
|
||||
export function flipMs(o: HalliGalliOptions): number | null {
|
||||
if (o.flipSeconds === null) return o.autoFlip ? (o.kidMode ? 8 : 3) * 1000 : null;
|
||||
return (o.kidMode ? 8 : o.flipSeconds) * 1000;
|
||||
}
|
||||
const deadlineFrom = (o: HalliGalliOptions, from: number): number | null => {
|
||||
const ms = flipMs(o);
|
||||
return ms === null ? null : from + ms;
|
||||
};
|
||||
/** Public key of a visible card; secretsOf uses the same form so leak checks are meaningful. */
|
||||
export const cardKey = (id: number): string => `hg${id}`;
|
||||
|
||||
@@ -116,7 +124,7 @@ function othersClockwise(s: S, p: PlayerId): PlayerId[] {
|
||||
function startTurn(s: S, p: PlayerId, now: number): void {
|
||||
s.turn = p;
|
||||
s.turnStartedAt = now;
|
||||
s.turnDeadline = now + flipMs(s.options);
|
||||
s.turnDeadline = deadlineFrom(s.options, now);
|
||||
s.pendingFlip = null;
|
||||
}
|
||||
|
||||
@@ -327,7 +335,7 @@ function tick(s: S, actor: PlayerId, ctx: Ctx): void {
|
||||
if (ctx.now >= s.ringWindow.openedAt + RING_WINDOW_MS) resolveWindow(s, ctx);
|
||||
return;
|
||||
}
|
||||
const due = (s.pendingFlip !== null && ctx.now >= s.flipAllowedAt) || ctx.now >= Math.max(s.turnDeadline, s.flipAllowedAt);
|
||||
const due = (s.pendingFlip !== null && ctx.now >= s.flipAllowedAt) || (s.turnDeadline !== null && ctx.now >= Math.max(s.turnDeadline, s.flipAllowedAt));
|
||||
if (actor === s.turn || due) flipOrQueue(s, s.turn, ctx);
|
||||
}
|
||||
|
||||
@@ -413,7 +421,7 @@ export const halliGalli: GameDefinition<S, A, HalliGalliView, HalliGalliOptions>
|
||||
officialDuel: false,
|
||||
turn: first,
|
||||
turnStartedAt: now,
|
||||
turnDeadline: countdownEndsAt + flipMs(options),
|
||||
turnDeadline: deadlineFrom(options, countdownEndsAt),
|
||||
flipAllowedAt: countdownEndsAt,
|
||||
pendingFlip: null,
|
||||
tableVersion: 0,
|
||||
@@ -544,9 +552,9 @@ export const halliGalli: GameDefinition<S, A, HalliGalliView, HalliGalliOptions>
|
||||
if (s.ringWindow) c.push(s.ringWindow.openedAt + RING_WINDOW_MS);
|
||||
else {
|
||||
if (s.pendingFlip) c.push(s.flipAllowedAt);
|
||||
c.push(Math.max(s.turnDeadline, s.flipAllowedAt));
|
||||
if (s.turnDeadline !== null) c.push(Math.max(s.turnDeadline, s.flipAllowedAt));
|
||||
}
|
||||
return Math.min(...c);
|
||||
return c.length ? Math.min(...c) : null;
|
||||
},
|
||||
|
||||
/** Only the turn player's clock drives the server tick (flips, guard, bell window, time limit). */
|
||||
|
||||
@@ -35,9 +35,10 @@ export const halliGalliOptionsSchema = z.object({
|
||||
timeLimitMin: lit<5 | 10 | 15 | null>(5, 10, 15, null)
|
||||
.default(10)
|
||||
.meta({ title: '전체 제한 시간', labels: { 5: '5분', 10: '10분', 15: '15분', null: '없음' } }),
|
||||
flipSeconds: lit<2 | 3 | 5 | 8>(2, 3, 5, 8)
|
||||
/** null = 무제한: the turn player flips whenever they like (자동 뒤집기 then keeps a 3-second pace, 어린이 모드 8). */
|
||||
flipSeconds: lit<2 | 3 | 5 | 8 | null>(2, 3, 5, 8, null)
|
||||
.default(3)
|
||||
.meta({ title: '뒤집기 제한 시간', labels: { 2: '2초', 3: '3초', 5: '5초', 8: '8초' } }),
|
||||
.meta({ title: '뒤집기 제한 시간', labels: { 2: '2초', 3: '3초', 5: '5초', 8: '8초', null: '무제한' } }),
|
||||
autoFlip: z.boolean().default(false).meta({ title: '카드를 자동으로 뒤집기(뒤집기 버튼 없음)' }),
|
||||
flipGuardMs: lit<400 | 600 | 1000>(400, 600, 1000)
|
||||
.default(600)
|
||||
@@ -135,7 +136,8 @@ export interface HalliGalliState {
|
||||
officialDuel: boolean;
|
||||
turn: PlayerId;
|
||||
turnStartedAt: number;
|
||||
turnDeadline: number;
|
||||
/** null = 무제한 뒤집기 시간 (nobody flips for the turn player unless they are away). */
|
||||
turnDeadline: number | null;
|
||||
flipAllowedAt: number;
|
||||
pendingFlip: PlayerId | null;
|
||||
tableVersion: number;
|
||||
@@ -188,8 +190,8 @@ export interface HalliGalliView {
|
||||
removed: number;
|
||||
countdownEndsAt: number;
|
||||
turnStartedAt: number;
|
||||
turnDeadline: number;
|
||||
flipTotalMs: number;
|
||||
turnDeadline: number | null;
|
||||
flipTotalMs: number | null;
|
||||
flipAllowedAt: number;
|
||||
/** The turn player's flip is queued behind the flip guard / bell window. */
|
||||
pendingFlip: boolean;
|
||||
|
||||
@@ -52,6 +52,18 @@ describe('whole games', () => {
|
||||
}, 60_000);
|
||||
}
|
||||
|
||||
test('모든 시간 무제한, 컴퓨터만: 설명·토론 끝내기·투표·맞히기를 해서 모두 끝나요', () => {
|
||||
const options = opts({ describeSeconds: null, discussionSeconds: null, voteSeconds: null, guessSeconds: null });
|
||||
for (const n of [3, 5, 8, 10]) {
|
||||
const r = liveBotPlayout(liar, liarBot, { players: seats(n, 0), options, seed: seedN(900 + n), isBot });
|
||||
expect(r.finished).toBe(true);
|
||||
expect(r.rejected).toEqual([]);
|
||||
const st = r.state as LiarState;
|
||||
expect(st.descriptions.every((d) => d.text !== null)).toBe(true);
|
||||
expect(r.elapsed).toBeGreaterThan(30_000);
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test('컴퓨터는 토론 때 말하고, 라이어 컴퓨터는 자기를 지목하지 않아요', () => {
|
||||
for (let s = 1; s <= 10; s++) {
|
||||
const r = liveBotPlayout(liar, liarBot, { players: seats(6, 0), seed: seedN(300 + s), isBot });
|
||||
|
||||
@@ -130,6 +130,15 @@ function matchAll(m: TopicModel, text: string): Map<string, number> {
|
||||
|
||||
// ---------------------------------------------------------------- the bot
|
||||
|
||||
/** How a computer paces a 무제한 phase: like the default clock of that phase. */
|
||||
const UNLIMITED_PACE_MS: Record<Exclude<LiarView['phase']['kind'], 'ended'>, number> = {
|
||||
reveal: 10_000,
|
||||
describe: 30_000,
|
||||
discussion: 90_000,
|
||||
vote: 30_000,
|
||||
guess: 30_000,
|
||||
};
|
||||
|
||||
class LiarBot {
|
||||
readonly v: LiarView;
|
||||
readonly me: PlayerId;
|
||||
@@ -197,8 +206,11 @@ class LiarBot {
|
||||
return this.v.phase.startedAt;
|
||||
}
|
||||
|
||||
/** Phase length; 무제한 phases are paced like the default clock (so a computer neither rushes nor stalls). */
|
||||
private get phaseLen(): number {
|
||||
return Math.max(1000, (this.v.phase.endsAt ?? this.phaseStart) - this.phaseStart);
|
||||
const ph = this.v.phase;
|
||||
if (ph.endsAt === null && ph.kind !== 'ended') return UNLIMITED_PACE_MS[ph.kind];
|
||||
return Math.max(1000, (ph.endsAt ?? this.phaseStart) - this.phaseStart);
|
||||
}
|
||||
|
||||
/** `lo..hi` seconds into the phase (scaled by pace), never later than `cap` of it. */
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
*
|
||||
* Phases run on the server clock like 마피아: every phase has `endsAt`, and the room applies the system-only
|
||||
* `phaseTimeout` there (one "driver" player; `timeoutNotBefore` keeps an away driver from firing it early).
|
||||
* 무제한 phases (`endsAt` null) end when everyone needed is done; a player away past the room's grace period
|
||||
* is passed by their own `phaseTimeout` (넘김 / no vote / wrong guess).
|
||||
* 제시어 확인 → 차례대로 한 문장 설명(바퀴 수만큼, 두 번째 바퀴는 거꾸로) → 자유 토론 → 투표(동점이면 동점자끼리 재투표 한 번,
|
||||
* 또 동점이면 라이어 승리) → 지목된 사람이 라이어면 제시어 맞히기 → 결과.
|
||||
*
|
||||
@@ -97,6 +99,8 @@ function speakerOf(s: LiarState): PlayerId | null {
|
||||
/** The liar is known to everybody once accused (guess phase) or at the end. */
|
||||
const liarKnown = (s: LiarState) => s.phase.kind === 'guess' || s.final !== null;
|
||||
|
||||
const endsIn = (now: number, sec: number | null) => (sec === null ? null : now + sec * 1000);
|
||||
|
||||
/** Starts the describe turn at `turn` of `round` (skipping people who left), or the next round, or the discussion. */
|
||||
function nextTurn(s: LiarState, now: number, round: number, turn: number): void {
|
||||
for (let r = round; r <= s.options.rounds; r++) {
|
||||
@@ -104,17 +108,17 @@ function nextTurn(s: LiarState, now: number, round: number, turn: number): void
|
||||
for (let t = r === round ? turn : 0; t < order.length; t++) {
|
||||
if (!isPresent(s, order[t])) continue;
|
||||
const fresh = s.phase.kind !== 'describe' || s.phase.round !== r;
|
||||
s.phase = { kind: 'describe', startedAt: now, endsAt: now + s.options.describeSeconds * 1000, round: r, turn: t };
|
||||
s.phase = { kind: 'describe', startedAt: now, endsAt: endsIn(now, s.options.describeSeconds), round: r, turn: t };
|
||||
if (fresh) pushEvent(s, now, { t: 'phase', kind: 'describe', round: r });
|
||||
return;
|
||||
}
|
||||
}
|
||||
s.phase = { kind: 'discussion', startedAt: now, endsAt: now + s.options.discussionSeconds * 1000, ready: [] };
|
||||
s.phase = { kind: 'discussion', startedAt: now, endsAt: endsIn(now, s.options.discussionSeconds), ready: [] };
|
||||
pushEvent(s, now, { t: 'phase', kind: 'discussion' });
|
||||
}
|
||||
|
||||
function startVote(s: LiarState, now: number, round: 1 | 2, candidates: PlayerId[]): void {
|
||||
s.phase = { kind: 'vote', startedAt: now, endsAt: now + s.options.voteSeconds * 1000, round, candidates, votes: {} };
|
||||
s.phase = { kind: 'vote', startedAt: now, endsAt: endsIn(now, s.options.voteSeconds), round, candidates, votes: {} };
|
||||
pushEvent(s, now, { t: 'phase', kind: 'vote', round });
|
||||
}
|
||||
|
||||
@@ -128,7 +132,48 @@ function voteTargets(s: LiarState, voter: PlayerId): PlayerId[] {
|
||||
/** Present players who can vote (someone whose only candidate is themselves sits the revote out). */
|
||||
const voters = (s: LiarState) => present(s).filter((p) => voteTargets(s, p.id).length > 0);
|
||||
|
||||
const allVoted = (s: LiarState) => s.phase.kind === 'vote' && voters(s).every((p) => s.phase.kind === 'vote' && s.phase.votes[p.id] !== undefined);
|
||||
/** Has voted (or, 무제한, was passed while away). */
|
||||
const hasVoted = (ph: Extract<Phase, { kind: 'vote' }>, p: PlayerId) => ph.votes[p] !== undefined || (ph.passed ?? []).includes(p);
|
||||
const allVoted = (s: LiarState) => s.phase.kind === 'vote' && voters(s).every((p) => s.phase.kind === 'vote' && hasVoted(s.phase, p.id));
|
||||
|
||||
/** 무제한 phase: who it still waits for (the speaker, 토론 끝내기, votes, the liar's guess). */
|
||||
function awaited(s: LiarState): PlayerId[] {
|
||||
const ph = s.phase;
|
||||
if (ph.kind === 'ended' || ph.endsAt !== null) return [];
|
||||
switch (ph.kind) {
|
||||
case 'describe':
|
||||
return [speakerOf(s)!];
|
||||
case 'discussion':
|
||||
case 'reveal':
|
||||
return present(s)
|
||||
.filter((p) => !ph.ready.includes(p.id))
|
||||
.map((p) => p.id);
|
||||
case 'vote':
|
||||
return voters(s)
|
||||
.filter((p) => !hasVoted(ph, p.id))
|
||||
.map((p) => p.id);
|
||||
case 'guess':
|
||||
return [s.liar];
|
||||
}
|
||||
}
|
||||
|
||||
/** 무제한: the room moved on for `p` (away past the grace period). */
|
||||
function pass(s: LiarState, now: number, p: PlayerId): void {
|
||||
const ph = s.phase;
|
||||
switch (ph.kind) {
|
||||
case 'discussion':
|
||||
ph.ready.push(p);
|
||||
if (present(s).every((x) => ph.ready.includes(x.id))) advance(s, now);
|
||||
return;
|
||||
case 'vote':
|
||||
(ph.passed ??= []).push(p);
|
||||
if (allVoted(s)) resolveVote(s, now);
|
||||
return;
|
||||
default:
|
||||
// describe: the speaker's turn is 넘김; guess: no answer (wrong).
|
||||
advance(s, now);
|
||||
}
|
||||
}
|
||||
|
||||
function finish(s: LiarState, now: number, winner: 'liar' | 'citizens', reason: WinReason): void {
|
||||
const word = s.word;
|
||||
@@ -176,7 +221,7 @@ function resolveVote(s: LiarState, now: number): void {
|
||||
const isLiar = accused === s.liar;
|
||||
pushEvent(s, now, { t: 'accused', p: accused, liar: isLiar });
|
||||
if (!isLiar) return finish(s, now, 'liar', 'escaped');
|
||||
s.phase = { kind: 'guess', startedAt: now, endsAt: now + s.options.guessSeconds * 1000 };
|
||||
s.phase = { kind: 'guess', startedAt: now, endsAt: endsIn(now, s.options.guessSeconds) };
|
||||
pushEvent(s, now, { t: 'phase', kind: 'guess' });
|
||||
}
|
||||
|
||||
@@ -273,6 +318,8 @@ function validate(s: LiarState, actor: PlayerId, a: LiarAction, ctx?: { now: num
|
||||
if (s.final || ph.kind === 'ended') return fail('게임이 이미 끝났어요.');
|
||||
switch (a.type) {
|
||||
case 'phaseTimeout':
|
||||
// 무제한: only for someone the phase waits on (the room passes a player away past the grace period).
|
||||
if (ph.endsAt === null) return awaited(s).includes(actor) ? ok : fail('아직 기다리는 중이에요.');
|
||||
return ctx && ctx.now < ph.endsAt ? fail('아직 시간이 남았어요.') : ok;
|
||||
case 'leave':
|
||||
return p.left ? fail('이미 나갔어요.') : ok;
|
||||
@@ -359,7 +406,7 @@ function view(s: LiarState, viewer: PlayerId | null): LiarView {
|
||||
readyNeeded: readyPhase ? present(s).length : 0,
|
||||
voteRound: ph.kind === 'vote' ? ph.round : null,
|
||||
candidates: ph.kind === 'vote' ? [...ph.candidates] : [],
|
||||
votedCount: ph.kind === 'vote' ? Object.keys(ph.votes).length : 0,
|
||||
votedCount: ph.kind === 'vote' ? voters(s).filter((p) => hasVoted(ph, p.id)).length : 0,
|
||||
liar: ph.kind === 'guess' ? s.liar : null,
|
||||
choices: ph.kind === 'guess' && s.options.guessMode === 'choice' ? topicById(s.topic).words.map((x) => x.word).sort((a, b) => a.localeCompare(b, 'ko')) : [],
|
||||
},
|
||||
@@ -368,7 +415,7 @@ function view(s: LiarState, viewer: PlayerId | null): LiarView {
|
||||
players: s.players.map((p) => ({
|
||||
id: p.id,
|
||||
left: p.left,
|
||||
voted: ph.kind === 'vote' && ph.votes[p.id] !== undefined,
|
||||
voted: ph.kind === 'vote' && hasVoted(ph, p.id),
|
||||
liar: known ? p.id === s.liar : null,
|
||||
})),
|
||||
descriptions: s.descriptions.map((d) => ({ ...d })),
|
||||
@@ -392,7 +439,7 @@ function activePlayers(s: LiarState): PlayerId[] {
|
||||
return [s.liar];
|
||||
case 'vote':
|
||||
return voters(s)
|
||||
.filter((p) => ph.votes[p.id] === undefined)
|
||||
.filter((p) => !hasVoted(ph, p.id))
|
||||
.map((p) => p.id);
|
||||
default:
|
||||
return present(s).map((p) => p.id);
|
||||
@@ -455,7 +502,8 @@ export const liar: Def = {
|
||||
const ph = s.phase;
|
||||
switch (a.type) {
|
||||
case 'phaseTimeout':
|
||||
advance(s, now);
|
||||
if (ph.kind !== 'ended' && ph.endsAt === null) pass(s, now, actor);
|
||||
else advance(s, now);
|
||||
break;
|
||||
case 'leave':
|
||||
leave(s, now, p);
|
||||
@@ -498,9 +546,10 @@ export const liar: Def = {
|
||||
return s.phase.kind === 'ended' ? null : s.phase.endsAt;
|
||||
},
|
||||
|
||||
/** One player drives the phase clock (the deadline is shared by everybody). */
|
||||
/** One player drives the phase clock (the deadline is shared by everybody); 무제한: those still awaited (only the away ones time out). */
|
||||
timeoutPlayers(s) {
|
||||
return s.phase.kind === 'ended' ? [] : [s.players[0]!.id];
|
||||
if (s.phase.kind === 'ended') return [];
|
||||
return s.phase.endsAt === null ? awaited(s) : [s.players[0]!.id];
|
||||
},
|
||||
|
||||
/** An away driver must not end a phase early. */
|
||||
@@ -540,7 +589,7 @@ export const liar: Def = {
|
||||
const p = P(s, player);
|
||||
if (!p || s.final || s.phase.kind === 'ended') return [];
|
||||
const out: LiarAction[] = [{ type: 'phaseTimeout' }];
|
||||
if (p.left) return out;
|
||||
if (p.left) return out.filter((a) => validate(s, player, a).ok);
|
||||
const me = myView(s, p);
|
||||
if (me.canChat) out.push({ type: 'chat', text: `m${s.seq}-${player}` });
|
||||
if (me.canReady) out.push({ type: 'ready' });
|
||||
|
||||
@@ -52,7 +52,7 @@ function reject(s: LiarState, actor: PlayerId, a: LiarAction, now?: number): str
|
||||
}
|
||||
const tick = (s: LiarState) => {
|
||||
if (s.phase.kind === 'ended') throw new Error('tick after the end');
|
||||
return act(s, s.players[0]!.id, { type: 'phaseTimeout' }, s.phase.endsAt);
|
||||
return act(s, s.players[0]!.id, { type: 'phaseTimeout' }, s.phase.endsAt!);
|
||||
};
|
||||
function until(s: LiarState, kind: LiarState['phase']['kind']): LiarState {
|
||||
for (let i = 0; i < 60 && s.phase.kind !== kind && s.phase.kind !== 'ended'; i++) s = tick(s);
|
||||
@@ -231,7 +231,7 @@ describe('차례대로 설명 (§5.2)', () => {
|
||||
|
||||
test('한 바퀴 옵션, 시간 초과는 넘김, 설명은 80자까지', () => {
|
||||
let s = tick(rig(3, { rounds: 1, describeSeconds: 15 }));
|
||||
expect(s.phase.kind === 'describe' && s.phase.endsAt - s.phase.startedAt).toBe(15_000);
|
||||
expect(s.phase.kind === 'describe' && s.phase.endsAt! - s.phase.startedAt).toBe(15_000);
|
||||
expect(reject(s, 'P0', { type: 'chat', text: '가'.repeat(81) })).toContain('80자');
|
||||
s = tick(s);
|
||||
expect(s.descriptions[0]).toMatchObject({ from: 'P0', text: null });
|
||||
@@ -381,6 +381,54 @@ describe('나가기 (§8.5)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('시간 무제한 (§8.5)', () => {
|
||||
const U = { describeSeconds: null, discussionSeconds: null, voteSeconds: null, guessSeconds: null };
|
||||
|
||||
test('설명·토론·투표·맞히기 모두 무제한: 마감 없이 할 일을 마칠 때까지, 기다리는 사람만 시간 초과 대상', () => {
|
||||
let s = tick(rig(3, { ...U, rounds: 1 }));
|
||||
expect(s.phase.kind === 'describe' && s.phase.endsAt).toBeNull();
|
||||
expect(liar.deadline!(s)).toBeNull();
|
||||
expect(liar.timeoutPlayers!(s)).toEqual(['P0']);
|
||||
expect(reject(s, 'P1', { type: 'phaseTimeout' })).toBe('아직 기다리는 중이에요.');
|
||||
for (const p of ['P0', 'P1', 'P2']) s = act(s, p, { type: 'chat', text: `${p} 설명` }, T0 + 3_600_000);
|
||||
expect(s.phase.kind).toBe('discussion');
|
||||
expect(liar.timeoutPlayers!(s)).toEqual(['P0', 'P1', 'P2']);
|
||||
for (const p of ['P0', 'P1', 'P2']) s = act(s, p, { type: 'ready' });
|
||||
expect(s.phase.kind).toBe('vote');
|
||||
s = votes(s, { P0: 'P2', P1: 'P2' });
|
||||
expect(liar.timeoutPlayers!(s)).toEqual(['P2']);
|
||||
s = act(s, 'P2', { type: 'vote', target: 'P0' });
|
||||
expect(s.phase.kind).toBe('guess');
|
||||
expect(liar.timeoutPlayers!(s)).toEqual(['P2']);
|
||||
s = act(s, 'P2', { type: 'guess', text: '수박' }, T0 + 7_200_000);
|
||||
expect(s.final!.reason).toBe('guessed');
|
||||
});
|
||||
|
||||
test('자리 비운 사람은 방의 유예 시간 뒤 자기 차례만 넘김: 설명 넘김·토론 끝·표 없음·답 없음', () => {
|
||||
let s = tick(rig(4, { ...U, rounds: 1 }));
|
||||
s = act(s, 'P0', liar.onTimeout(s, 'P0'));
|
||||
expect(s.descriptions[0]).toMatchObject({ from: 'P0', text: null });
|
||||
for (const p of ['P1', 'P2', 'P3']) s = act(s, p, { type: 'chat', text: `${p} 설명` });
|
||||
for (const p of ['P1', 'P2', 'P3']) s = act(s, p, { type: 'ready' });
|
||||
s = act(s, 'P0', liar.onTimeout(s, 'P0'));
|
||||
expect(s.phase.kind).toBe('vote');
|
||||
s = votes(s, { P1: 'P3', P2: 'P3', P3: 'P1' });
|
||||
expect(liar.view(s, null).players.find((p) => p.id === 'P0')!.voted).toBe(false);
|
||||
s = act(s, 'P0', liar.onTimeout(s, 'P0'));
|
||||
expect(lastEv(s, 'vote')).toMatchObject({ accused: 'P3', votes: { P1: 'P3', P2: 'P3', P3: 'P1' } });
|
||||
s = act(s, 'P3', liar.onTimeout(s, 'P3'));
|
||||
expect(s.final).toMatchObject({ winner: 'citizens', reason: 'caught', guess: null });
|
||||
});
|
||||
|
||||
test('무작위 대국(모두 무제한)도 끝나요', () => {
|
||||
for (let k = 1; k <= playoutSeeds(40); k++) {
|
||||
const n = 3 + (k % 8);
|
||||
const r = randomPlayout(liar, { players: ids(n), options: opts(U), seed: seedN(5000 + k), maxSteps: 3000 });
|
||||
expect(r.finished).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- engine checks
|
||||
|
||||
describe('무작위 대국 (엔진 공통 검사)', () => {
|
||||
|
||||
@@ -5,9 +5,11 @@ import { TOPIC_IDS, TOPIC_KO, type TopicId } from './topics';
|
||||
|
||||
export { TOPIC_IDS, TOPIC_KO, type TopicId } from './topics';
|
||||
|
||||
const lit = <T extends number>(...vals: T[]) =>
|
||||
const lit = <T extends number | null>(...vals: T[]) =>
|
||||
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
||||
const secLabels = (...vals: number[]) => Object.fromEntries(vals.map((v) => [v, `${v}초`]));
|
||||
/** Labels plus 무제한 (null): that phase has no clock (§8.5). */
|
||||
const secLabelsU = (unl: string, ...vals: number[]) => ({ ...secLabels(...vals), null: unl });
|
||||
|
||||
export const liarOptionsSchema = z.object({
|
||||
topic: z
|
||||
@@ -18,22 +20,23 @@ export const liarOptionsSchema = z.object({
|
||||
rounds: lit(1, 2)
|
||||
.default(2)
|
||||
.meta({ title: '설명 바퀴 수', labels: { 1: '한 바퀴', 2: '두 바퀴(두 번째는 거꾸로)' } }),
|
||||
describeSeconds: lit(15, 20, 30, 45, 60)
|
||||
/** null = 무제한 (each such phase ends when everyone needed is done; away players are passed after the room's grace period). */
|
||||
describeSeconds: lit<15 | 20 | 30 | 45 | 60 | null>(15, 20, 30, 45, 60, null)
|
||||
.default(30)
|
||||
.meta({ title: '한 사람 설명 시간', labels: secLabels(15, 20, 30, 45, 60) }),
|
||||
discussionSeconds: lit(30, 60, 90, 120, 180)
|
||||
.meta({ title: '한 사람 설명 시간', labels: secLabelsU('무제한(설명을 보낼 때까지)', 15, 20, 30, 45, 60) }),
|
||||
discussionSeconds: lit<30 | 60 | 90 | 120 | 180 | null>(30, 60, 90, 120, 180, null)
|
||||
.default(90)
|
||||
.meta({ title: '자유 토론 시간', labels: secLabels(30, 60, 90, 120, 180) }),
|
||||
voteSeconds: lit(15, 20, 30, 45)
|
||||
.meta({ title: '자유 토론 시간', labels: secLabelsU('무제한(모두 토론 끝내기를 누를 때까지)', 30, 60, 90, 120, 180) }),
|
||||
voteSeconds: lit<15 | 20 | 30 | 45 | null>(15, 20, 30, 45, null)
|
||||
.default(30)
|
||||
.meta({ title: '투표 시간', labels: secLabels(15, 20, 30, 45) }),
|
||||
.meta({ title: '투표 시간', labels: secLabelsU('무제한(모두 투표할 때까지)', 15, 20, 30, 45) }),
|
||||
guessMode: z
|
||||
.enum(['text', 'choice'])
|
||||
.default('text')
|
||||
.meta({ title: '라이어의 정답 맞히기', labels: { text: '직접 적기', choice: '주제 단어 목록에서 고르기' } }),
|
||||
guessSeconds: lit(20, 30, 45, 60)
|
||||
guessSeconds: lit<20 | 30 | 45 | 60 | null>(20, 30, 45, 60, null)
|
||||
.default(30)
|
||||
.meta({ title: '정답 맞히기 시간', labels: secLabels(20, 30, 45, 60) }),
|
||||
.meta({ title: '정답 맞히기 시간', labels: secLabelsU('무제한(라이어가 답할 때까지)', 20, 30, 45, 60) }),
|
||||
kidSafeChat: z.boolean().default(true).meta({ title: '고운 말 필터(욕설·링크·전화번호 막기)' }),
|
||||
});
|
||||
export type LiarOptions = z.infer<typeof liarOptionsSchema>;
|
||||
@@ -54,10 +57,12 @@ export type LiarAction = LiarClientAction | { type: 'phaseTimeout' } | { type: '
|
||||
|
||||
export type Phase =
|
||||
| { kind: 'reveal'; startedAt: number; endsAt: number; ready: PlayerId[] }
|
||||
| { kind: 'describe'; startedAt: number; endsAt: number; round: number; turn: number }
|
||||
| { kind: 'discussion'; startedAt: number; endsAt: number; ready: PlayerId[] }
|
||||
| { kind: 'vote'; startedAt: number; endsAt: number; round: 1 | 2; candidates: PlayerId[]; votes: Record<PlayerId, PlayerId> }
|
||||
| { kind: 'guess'; startedAt: number; endsAt: number }
|
||||
// endsAt null = 무제한: describe/guess wait for the speaker/liar, discussion for everyone's 「투표하자」, vote for every vote.
|
||||
| { kind: 'describe'; startedAt: number; endsAt: number | null; round: number; turn: number }
|
||||
| { kind: 'discussion'; startedAt: number; endsAt: number | null; ready: PlayerId[] }
|
||||
/** `passed`: 무제한 only, voters the room moved on while away (no vote). */
|
||||
| { kind: 'vote'; startedAt: number; endsAt: number | null; round: 1 | 2; candidates: PlayerId[]; votes: Record<PlayerId, PlayerId>; passed?: PlayerId[] }
|
||||
| { kind: 'guess'; startedAt: number; endsAt: number | null }
|
||||
| { kind: 'ended' };
|
||||
export type PhaseKind = Phase['kind'];
|
||||
|
||||
|
||||
@@ -64,6 +64,17 @@ describe('whole games', () => {
|
||||
}, 60_000);
|
||||
}
|
||||
|
||||
test('every phase 무제한, computers only: they press 토론 끝내기·밤 마치기·반론 마치기 and vote, so every game ends', () => {
|
||||
const options = opts({ discussionPerAlive: null, voteSeconds: null, defenseSeconds: null, confirmSeconds: null, nightSeconds: null });
|
||||
for (const n of [4, 6, 9, 12]) {
|
||||
const r = liveBotPlayout(mafia, mafiaBot, { players: seats(n, 0), options, seed: seedN(700 + n), isBot });
|
||||
expect(r.finished).toBe(true);
|
||||
expect(r.rejected).toEqual([]);
|
||||
// Paced like the default clocks: neither instant nor endless.
|
||||
expect(r.elapsed).toBeGreaterThan(60_000);
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test('a mafia computer never points at its own team in the day chat', () => {
|
||||
for (let s = 1; s <= 12; s++) {
|
||||
const r = liveBotPlayout(mafia, mafiaBot, { players: seats(8, 0), seed: seedN(500 + s), isBot });
|
||||
@@ -118,7 +129,7 @@ describe('timing and answers', () => {
|
||||
const rng = SeededRng.fromSeed(seedN(10));
|
||||
let now = 0;
|
||||
while (st.phase.kind !== kind) {
|
||||
now = st.phase.kind === 'ended' ? now : st.phase.endsAt;
|
||||
now = st.phase.kind === 'ended' ? now : st.phase.endsAt!;
|
||||
st = mafia.apply(st, players[0]!, { type: 'phaseTimeout' }, { rng, now }).state;
|
||||
}
|
||||
return { st, now, rng, players };
|
||||
@@ -131,7 +142,7 @@ describe('timing and answers', () => {
|
||||
const quick = firstAction(st, bot, { smart: true, pace: 0.7, chatty: 0.8 }, names, 'vote')!;
|
||||
const slow = firstAction(st, bot, { smart: true, pace: 1.5, chatty: 0.8 }, names, 'vote')!;
|
||||
expect(quick.at).toBeLessThan(slow.at);
|
||||
expect(slow.at).toBeLessThan(st.options.voteSeconds * 1000);
|
||||
expect(slow.at).toBeLessThan(st.options.voteSeconds! * 1000);
|
||||
});
|
||||
|
||||
test('asked "컴퓨터 3 직업 뭐야?", computer 3 answers within seconds — and a mafia says it is a citizen', () => {
|
||||
|
||||
@@ -148,6 +148,17 @@ interface Mention {
|
||||
tail: string;
|
||||
}
|
||||
|
||||
/** How a computer paces a 무제한 phase: like the default clock of that phase. */
|
||||
const UNLIMITED_PACE_MS: Record<Exclude<MafiaView['phase']['kind'], 'ended'>, number> = {
|
||||
roleReveal: 8_000,
|
||||
greeting: 60_000,
|
||||
discussion: 90_000,
|
||||
vote: 20_000,
|
||||
defense: 20_000,
|
||||
confirm: 10_000,
|
||||
night: 30_000,
|
||||
};
|
||||
|
||||
class Reader {
|
||||
readonly v: MafiaView;
|
||||
readonly me: PlayerId;
|
||||
@@ -305,8 +316,11 @@ class MafiaBot {
|
||||
return this.v.phase.startedAt;
|
||||
}
|
||||
|
||||
/** Phase length; 무제한 phases are paced like the default clock (so a computer neither rushes nor stalls). */
|
||||
private get phaseLen(): number {
|
||||
return Math.max(1000, (this.v.phase.endsAt ?? this.phaseStart) - this.phaseStart);
|
||||
const ph = this.v.phase;
|
||||
if (ph.endsAt === null && ph.kind !== 'ended') return UNLIMITED_PACE_MS[ph.kind];
|
||||
return Math.max(1000, (ph.endsAt ?? this.phaseStart) - this.phaseStart);
|
||||
}
|
||||
|
||||
/** A moment inside the phase: `lo..hi` seconds after it started (scaled by pace), never later than `cap` of it. */
|
||||
@@ -512,6 +526,8 @@ class MafiaBot {
|
||||
if (k === 'defense' && v.phase.accused === this.me) {
|
||||
out.push({ key: key('def1'), due: this.inPhase(1.5, 4, 'def1'), make: () => this.say('day', this.defenseLine(true)) });
|
||||
if (this.smart || this.h('def2', v.day) < 0.5) out.push({ key: key('def2'), due: this.inPhase(7, 12, 'def2', 0.75), make: () => this.say('day', this.defenseLine(false)) });
|
||||
// 무제한: 반론 마치기 after the last line.
|
||||
if (this.my.canReady) out.push({ key: key('defEnd'), due: this.inPhase(13, 17, 'defEnd', 0.95), make: () => ({ type: 'readyEarly' }) });
|
||||
}
|
||||
|
||||
if (k === 'confirm' && this.my.canConfirm && this.my.ballot === null) {
|
||||
@@ -530,6 +546,8 @@ class MafiaBot {
|
||||
}
|
||||
|
||||
if (k === 'night') out.push(...this.night(key));
|
||||
// 무제한 night: 밤 마치기 after the night action (its latest time is earlier for the same pace).
|
||||
if (k === 'night' && this.my.canReady) out.push({ key: key('nready'), due: this.inPhase(18, 24, 'nready', 0.95), make: () => ({ type: 'readyEarly' }) });
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
*
|
||||
* The server runs the phases: every phase has `endsAt`; the room timer applies the system-only
|
||||
* `phaseTimeout` there (one "driver" player, `timeoutNotBefore` keeps away players from firing it
|
||||
* early). Chat lives in the state and the view filters it by channel permission (§5.6, §8.3).
|
||||
* early). 무제한 phases (`endsAt` null) end when everyone needed is done instead; a player away past the
|
||||
* room's grace period is passed by their own `phaseTimeout`. Chat lives in the state and the view filters
|
||||
* it by channel permission (§5.6, §8.3).
|
||||
*/
|
||||
import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng, type Validation } from '@bg/engine';
|
||||
import {
|
||||
@@ -126,13 +128,73 @@ const alive = (s: MafiaState) => s.players.filter((p) => p.alive);
|
||||
const isAlive = (s: MafiaState, id: PlayerId | null) => !!id && !!P(s, id)?.alive;
|
||||
type NightPhase = Extract<Phase, { kind: 'night' }>;
|
||||
|
||||
function discussionMs(s: MafiaState): number {
|
||||
/** Discussion length; null = 무제한. */
|
||||
function discussionMs(s: MafiaState): number | null {
|
||||
const o = s.options;
|
||||
if (o.discussionPerAlive === null) return null;
|
||||
const lo = o.discussionMin;
|
||||
const hi = Math.max(o.discussionMin, o.discussionMax);
|
||||
return Math.min(hi, Math.max(lo, alive(s).length * o.discussionPerAlive)) * 1000;
|
||||
}
|
||||
|
||||
const ends = (now: number, ms: number | null) => (ms === null ? null : now + ms);
|
||||
const endsIn = (now: number, sec: number | null) => (sec === null ? null : now + sec * 1000);
|
||||
|
||||
/** 무제한 phase: the living players it still waits for (votes, ballots, 토론 끝내기 / 밤 마치기, the accused's 반론 마치기). */
|
||||
function awaited(s: MafiaState): PlayerId[] {
|
||||
const ph = s.phase;
|
||||
if (ph.kind === 'ended' || ph.endsAt !== null) return [];
|
||||
const live = alive(s).map((p) => p.id);
|
||||
switch (ph.kind) {
|
||||
case 'greeting':
|
||||
case 'discussion':
|
||||
return live.filter((p) => !ph.ready.includes(p));
|
||||
case 'night':
|
||||
return live.filter((p) => !(ph.ready ?? []).includes(p));
|
||||
case 'vote':
|
||||
return live.filter((p) => ph.votes[p] === undefined);
|
||||
case 'defense':
|
||||
return isAlive(s, ph.accused) ? [ph.accused] : [];
|
||||
case 'confirm':
|
||||
return live.filter((p) => p !== ph.accused && ph.ballots[p] === undefined && !(ph.passed ?? []).includes(p));
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** 무제한: the phase ends once nobody is awaited. */
|
||||
function settle(s: MafiaState, now: number, rng: Rng): void {
|
||||
const ph = s.phase;
|
||||
if (s.winner || ph.kind === 'ended' || ph.endsAt !== null || ph.kind === 'roleReveal') return;
|
||||
if (awaited(s).length === 0) advance(s, now, rng);
|
||||
}
|
||||
|
||||
/** 무제한: the room moved on for `p` (away past the grace period): no vote / no ballot / done. */
|
||||
function pass(s: MafiaState, now: number, rng: Rng, p: PlayerId): void {
|
||||
const ph = s.phase;
|
||||
switch (ph.kind) {
|
||||
case 'greeting':
|
||||
case 'discussion':
|
||||
if (!ph.ready.includes(p)) ph.ready.push(p);
|
||||
break;
|
||||
case 'night':
|
||||
(ph.ready ??= []).push(p);
|
||||
break;
|
||||
case 'vote':
|
||||
ph.votes[p] = 'abstain';
|
||||
break;
|
||||
case 'defense':
|
||||
advance(s, now, rng);
|
||||
return;
|
||||
case 'confirm':
|
||||
(ph.passed ??= []).push(p);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
settle(s, now, rng);
|
||||
}
|
||||
|
||||
function pushEvent(s: MafiaState, now: number, e: DistributiveOmit<PublicEvent, 'n' | 'at' | 'day'>, day = s.day): void {
|
||||
s.events.push({ ...e, n: s.events.length + 1, at: now, day } as PublicEvent);
|
||||
}
|
||||
@@ -144,13 +206,14 @@ function startPhase(s: MafiaState, now: number, kind: 'greeting' | 'discussion'
|
||||
s.phase = { kind, startedAt: now, endsAt: now + GREETING_MS, ready: [] };
|
||||
break;
|
||||
case 'discussion':
|
||||
s.phase = { kind, startedAt: now, endsAt: now + discussionMs(s), adjustedBy: [], ready: [] };
|
||||
s.phase = { kind, startedAt: now, endsAt: ends(now, discussionMs(s)), adjustedBy: [], ready: [] };
|
||||
break;
|
||||
case 'vote':
|
||||
s.phase = { kind, startedAt: now, endsAt: now + s.options.voteSeconds * 1000, votes: {} };
|
||||
s.phase = { kind, startedAt: now, endsAt: endsIn(now, s.options.voteSeconds), votes: {} };
|
||||
break;
|
||||
case 'night':
|
||||
s.phase = { kind, startedAt: now, endsAt: now + s.options.nightSeconds * 1000, mafiaTarget: null, mafiaPickedBy: null, investigate: null, heal: null, mediumPeek: null };
|
||||
s.phase = { kind, startedAt: now, endsAt: endsIn(now, s.options.nightSeconds), mafiaTarget: null, mafiaPickedBy: null, investigate: null, heal: null, mediumPeek: null };
|
||||
if (s.phase.endsAt === null) s.phase.ready = [];
|
||||
break;
|
||||
}
|
||||
pushEvent(s, now, { t: 'phase', kind });
|
||||
@@ -318,7 +381,7 @@ function advance(s: MafiaState, now: number, rng: Rng): void {
|
||||
case 'vote': {
|
||||
const accused = resolveVote(s, now);
|
||||
if (accused) {
|
||||
s.phase = { kind: 'defense', startedAt: now, endsAt: now + s.options.defenseSeconds * 1000, accused };
|
||||
s.phase = { kind: 'defense', startedAt: now, endsAt: endsIn(now, s.options.defenseSeconds), accused };
|
||||
pushEvent(s, now, { t: 'phase', kind: 'defense' });
|
||||
return;
|
||||
}
|
||||
@@ -326,7 +389,7 @@ function advance(s: MafiaState, now: number, rng: Rng): void {
|
||||
return;
|
||||
}
|
||||
case 'defense':
|
||||
s.phase = { kind: 'confirm', startedAt: now, endsAt: now + s.options.confirmSeconds * 1000, accused: ph.accused, ballots: {} };
|
||||
s.phase = { kind: 'confirm', startedAt: now, endsAt: endsIn(now, s.options.confirmSeconds), accused: ph.accused, ballots: {} };
|
||||
pushEvent(s, now, { t: 'phase', kind: 'confirm' });
|
||||
return;
|
||||
case 'confirm':
|
||||
@@ -450,6 +513,8 @@ function validate(s: MafiaState, actor: PlayerId, a: MafiaAction, ctx?: { now: n
|
||||
if (ph.kind === 'ended') return fail('게임이 이미 끝났어요.');
|
||||
switch (a.type) {
|
||||
case 'phaseTimeout':
|
||||
// 무제한: only for someone the phase waits on (the room passes a player away past the grace period).
|
||||
if (ph.endsAt === null) return awaited(s).includes(actor) ? ok : fail('아직 기다리는 중이에요.');
|
||||
return ctx && ctx.now < ph.endsAt ? fail('아직 시간이 남았어요.') : ok;
|
||||
case 'leave':
|
||||
return p.alive ? ok : fail('이미 탈락했어요.');
|
||||
@@ -470,9 +535,12 @@ function validate(s: MafiaState, actor: PlayerId, a: MafiaAction, ctx?: { now: n
|
||||
case 'adjustTime':
|
||||
if (ph.kind !== 'discussion') return fail('토론 시간에만 시간을 바꿀 수 있어요.');
|
||||
if (!s.options.timeAdjust) return fail('이 방은 토론 시간을 바꿀 수 없어요.');
|
||||
if (ph.endsAt === null) return fail('이 방은 토론 시간이 무제한이에요.');
|
||||
if (ph.adjustedBy.includes(actor)) return fail('시간 바꾸기는 하루에 한 번만 할 수 있어요.');
|
||||
return a.delta === 15 || a.delta === -15 ? ok : fail('15초씩만 바꿀 수 있어요.');
|
||||
case 'readyEarly':
|
||||
if (ph.kind === 'night' && ph.endsAt === null) return (ph.ready ?? []).includes(actor) ? fail('이미 밤 마치기를 눌렀어요.') : ok;
|
||||
if (ph.kind === 'defense' && ph.endsAt === null) return ph.accused === actor ? ok : fail('지목된 사람만 반론을 마칠 수 있어요.');
|
||||
if (ph.kind !== 'discussion' && ph.kind !== 'greeting') return fail('지금은 토론 시간이 아니에요.');
|
||||
return ph.ready.includes(actor) ? fail('이미 토론 끝내기를 눌렀어요.') : ok;
|
||||
case 'vote':
|
||||
@@ -534,6 +602,8 @@ function myView(s: MafiaState, me: PlayerState): MyView {
|
||||
const ph = s.phase;
|
||||
const mates = me.role === 'mafia' || me.role === 'lover' ? s.players.filter((p) => p.role === me.role && p.id !== me.id).map((p) => p.id) : [];
|
||||
const day = ph.kind === 'greeting' || ph.kind === 'discussion';
|
||||
const nightReady = ph.kind === 'night' && ph.endsAt === null ? (ph.ready ?? []) : null;
|
||||
const defenseEnd = ph.kind === 'defense' && ph.endsAt === null && ph.accused === me.id;
|
||||
return {
|
||||
role: me.role,
|
||||
team: teamOf(me.role),
|
||||
@@ -543,15 +613,24 @@ function myView(s: MafiaState, me: PlayerState): MyView {
|
||||
voteTargets: ph.kind === 'vote' && me.alive ? alive(s).filter((p) => p.id !== me.id).map((p) => p.id) : [],
|
||||
ballot: ph.kind === 'confirm' && me.alive ? (ph.ballots[me.id] ?? null) : null,
|
||||
canConfirm: ph.kind === 'confirm' && me.alive && ph.accused !== me.id,
|
||||
canAdjust: ph.kind === 'discussion' && me.alive && s.options.timeAdjust && !ph.adjustedBy.includes(me.id),
|
||||
canReady: day && me.alive && !ph.ready.includes(me.id),
|
||||
ready: day && ph.ready.includes(me.id),
|
||||
canAdjust: ph.kind === 'discussion' && ph.endsAt !== null && me.alive && s.options.timeAdjust && !ph.adjustedBy.includes(me.id),
|
||||
canReady: me.alive && ((day && !ph.ready.includes(me.id)) || (nightReady !== null && !nightReady.includes(me.id)) || defenseEnd),
|
||||
ready: (day && ph.ready.includes(me.id)) || (nightReady?.includes(me.id) ?? false),
|
||||
night: ph.kind === 'night' && me.alive ? nightView(s, me) : null,
|
||||
results: s.privateResults.filter((r) => r.to === me.id),
|
||||
idleWarning: me.alive && !s.winner && me.idleDays >= AWAY_DAYS - 1 && !me.activeToday,
|
||||
};
|
||||
}
|
||||
|
||||
/** Ready / done counts for the phase banner (무제한 vote, ballots and night too). */
|
||||
function doneCounts(s: MafiaState, day: boolean): { readyCount: number; readyNeeded: number } {
|
||||
const ph = s.phase;
|
||||
if (day && (ph.kind === 'greeting' || ph.kind === 'discussion')) return { readyCount: ph.ready.length, readyNeeded: alive(s).length };
|
||||
if (ph.kind === 'ended' || ph.endsAt !== null || (ph.kind !== 'vote' && ph.kind !== 'confirm' && ph.kind !== 'night')) return { readyCount: 0, readyNeeded: 0 };
|
||||
const need = ph.kind === 'confirm' ? alive(s).filter((p) => p.id !== ph.accused).length : alive(s).length;
|
||||
return { readyCount: need - awaited(s).length, readyNeeded: need };
|
||||
}
|
||||
|
||||
function view(s: MafiaState, viewer: PlayerId | null): MafiaView {
|
||||
const me = viewer ? (P(s, viewer) ?? null) : null;
|
||||
const ph = s.phase;
|
||||
@@ -573,8 +652,7 @@ function view(s: MafiaState, viewer: PlayerId | null): MafiaView {
|
||||
endsAt: ph.kind === 'ended' ? null : ph.endsAt,
|
||||
accused: ph.kind === 'defense' || ph.kind === 'confirm' ? ph.accused : null,
|
||||
adjustedBy: ph.kind === 'discussion' ? [...ph.adjustedBy] : [],
|
||||
readyCount: day ? ph.ready.length : 0,
|
||||
readyNeeded: day ? alive(s).length : 0,
|
||||
...doneCounts(s, day),
|
||||
},
|
||||
players: s.players.map((p) => {
|
||||
const known = roleKnown(s, p, me);
|
||||
@@ -661,7 +739,8 @@ export const mafia: Def = {
|
||||
if (a.type !== 'phaseTimeout' && a.type !== 'leave') p.activeToday = true;
|
||||
switch (a.type) {
|
||||
case 'phaseTimeout':
|
||||
advance(s, now, rng);
|
||||
if (ph.kind !== 'ended' && ph.endsAt === null) pass(s, now, rng, actor);
|
||||
else advance(s, now, rng);
|
||||
break;
|
||||
case 'leave':
|
||||
leave(s, now, rng, p);
|
||||
@@ -676,10 +755,19 @@ export const mafia: Def = {
|
||||
case 'adjustTime':
|
||||
if (ph.kind !== 'discussion') throw new Error('mafia: adjustTime outside discussion');
|
||||
ph.adjustedBy.push(actor);
|
||||
if (ph.endsAt === null) throw new Error('mafia: adjustTime in a 무제한 discussion');
|
||||
ph.endsAt = a.delta > 0 ? ph.endsAt + ADJUST_MS : Math.max(ph.endsAt - ADJUST_MS, Math.min(ph.endsAt, now + ADJUST_FLOOR_MS));
|
||||
pushEvent(s, now, { t: 'adjust', p: actor, delta: a.delta });
|
||||
break;
|
||||
case 'readyEarly':
|
||||
if (ph.kind === 'defense') {
|
||||
advance(s, now, rng);
|
||||
break;
|
||||
}
|
||||
if (ph.kind === 'night') {
|
||||
(ph.ready ??= []).push(actor);
|
||||
break;
|
||||
}
|
||||
if (ph.kind !== 'discussion' && ph.kind !== 'greeting') throw new Error('mafia: readyEarly outside discussion');
|
||||
ph.ready.push(actor);
|
||||
if (alive(s).every((x) => ph.ready.includes(x.id))) advance(s, now, rng);
|
||||
@@ -704,6 +792,7 @@ export const mafia: Def = {
|
||||
ph[a.type] = a.target;
|
||||
break;
|
||||
}
|
||||
if (a.type !== 'chat') settle(s, now, rng);
|
||||
// Only public announcements become events (chat and night choices stay in the filtered view).
|
||||
const events: GameEvent[] = s.events.slice(before).map((e) => ({ ...e, type: e.t }));
|
||||
return { state: s, events };
|
||||
@@ -717,9 +806,10 @@ export const mafia: Def = {
|
||||
return s.phase.kind === 'ended' ? null : s.phase.endsAt;
|
||||
},
|
||||
|
||||
/** One player drives the phase clock (the deadline is shared by everybody). */
|
||||
/** One player drives the phase clock (the deadline is shared by everybody); 무제한: those still awaited (only the away ones time out). */
|
||||
timeoutPlayers(s) {
|
||||
return s.phase.kind === 'ended' ? [] : [s.players[0]!.id];
|
||||
if (s.phase.kind === 'ended') return [];
|
||||
return s.phase.endsAt === null ? awaited(s) : [s.players[0]!.id];
|
||||
},
|
||||
|
||||
/** An away driver must not end a phase early. */
|
||||
@@ -756,7 +846,7 @@ export const mafia: Def = {
|
||||
if (!p || s.winner || s.phase.kind === 'ended') return [];
|
||||
const out: MafiaAction[] = [{ type: 'phaseTimeout' }];
|
||||
for (const ch of CHANNELS) if (!writeBlock(s, p, ch)) out.push({ type: 'chat', channel: ch, text: `m${s.seq}-${player}-${ch}` });
|
||||
if (!p.alive) return out;
|
||||
if (!p.alive) return out.filter((a) => validate(s, player, a).ok);
|
||||
const ph = s.phase;
|
||||
const me = myView(s, p);
|
||||
if (me.canReady) out.push({ type: 'readyEarly' });
|
||||
@@ -781,4 +871,4 @@ export const mafia: Def = {
|
||||
},
|
||||
};
|
||||
|
||||
export const _internal = { canRead, writeBlock, roleKnown, nightTargets, discussionMs };
|
||||
export const _internal = { canRead, writeBlock, roleKnown, nightTargets, discussionMs, awaited };
|
||||
|
||||
@@ -46,7 +46,7 @@ function reject(s: MafiaState, actor: PlayerId, a: MafiaAction, now?: number): s
|
||||
/** The phase clock runs out. */
|
||||
function tick(s: MafiaState): MafiaState {
|
||||
if (s.phase.kind === 'ended') throw new Error('tick after the end');
|
||||
return act(s, s.players[0]!.id, { type: 'phaseTimeout' }, s.phase.endsAt);
|
||||
return act(s, s.players[0]!.id, { type: 'phaseTimeout' }, s.phase.endsAt!);
|
||||
}
|
||||
/** Ticks until `kind` (stops early if the game ends). */
|
||||
function until(s: MafiaState, kind: MafiaState['phase']['kind']): MafiaState {
|
||||
@@ -135,13 +135,13 @@ describe('직업 배분 (§4)', () => {
|
||||
|
||||
test('토론 시간 = clamp(생존자 × 값, 최소, 최대)', () => {
|
||||
const s = until(busy(until(rig(['mafia', 'police', 'doctor', 'citizen', 'citizen']), 'night')), 'discussion');
|
||||
expect(s.phase.kind === 'discussion' && s.phase.endsAt - s.phase.startedAt).toBe(75_000); // 5 × 15
|
||||
expect(s.phase.kind === 'discussion' && s.phase.endsAt! - s.phase.startedAt).toBe(75_000); // 5 × 15
|
||||
let t = until(rig(['mafia', 'police', 'doctor', 'citizen'], { discussionPerAlive: 10, discussionMin: 60 }), 'night');
|
||||
t = tick(t);
|
||||
expect(t.phase.kind === 'discussion' && t.phase.endsAt - t.phase.startedAt).toBe(60_000);
|
||||
expect(t.phase.kind === 'discussion' && t.phase.endsAt! - t.phase.startedAt).toBe(60_000);
|
||||
let u = until(rig(['mafia', 'mafia', 'mafia', 'police', 'doctor', 'citizen', 'citizen', 'citizen', 'citizen', 'citizen', 'citizen', 'citizen'], { discussionPerAlive: 20, discussionMax: 120 }), 'night');
|
||||
u = tick(u);
|
||||
expect(u.phase.kind === 'discussion' && u.phase.endsAt - u.phase.startedAt).toBe(120_000);
|
||||
expect(u.phase.kind === 'discussion' && u.phase.endsAt! - u.phase.startedAt).toBe(120_000);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -610,17 +610,17 @@ describe('시간 조절·자리 비움·나가기 (§5.2, §8.5)', () => {
|
||||
test('timeAdjust: 1인 1일 1회, -15초로 5초 미만 내려가지 않음', () => {
|
||||
let s = day2();
|
||||
const ph0 = s.phase as Extract<MafiaState['phase'], { kind: 'discussion' }>;
|
||||
const end0 = ph0.endsAt;
|
||||
const end0 = ph0.endsAt!;
|
||||
s = act(s, 'P1', { type: 'adjustTime', delta: 15 });
|
||||
expect((s.phase as typeof ph0).endsAt).toBe(end0 + 15_000);
|
||||
expect(reject(s, 'P1', { type: 'adjustTime', delta: -15 })).toBe('시간 바꾸기는 하루에 한 번만 할 수 있어요.');
|
||||
expect(lastEv(s, 'adjust')).toMatchObject({ p: 'P1', delta: 15 });
|
||||
// 끝나기 8초 전에 -15 → 5초 남김
|
||||
s = act(s, 'P2', { type: 'adjustTime', delta: -15 }, (s.phase as typeof ph0).endsAt - 8_000);
|
||||
s = act(s, 'P2', { type: 'adjustTime', delta: -15 }, (s.phase as typeof ph0).endsAt! - 8_000);
|
||||
const now = end0 + 15_000 - 8_000;
|
||||
expect((s.phase as typeof ph0).endsAt).toBe(now + 5_000);
|
||||
// 이미 5초 미만이면 그대로
|
||||
s = act(s, 'P3', { type: 'adjustTime', delta: -15 }, (s.phase as typeof ph0).endsAt - 3_000);
|
||||
s = act(s, 'P3', { type: 'adjustTime', delta: -15 }, (s.phase as typeof ph0).endsAt! - 3_000);
|
||||
expect((s.phase as typeof ph0).endsAt).toBe(now + 5_000);
|
||||
expect(mafia.view(s, null).phase.adjustedBy).toEqual(['P1', 'P2', 'P3']);
|
||||
// 다음 날에는 다시 가능
|
||||
@@ -691,6 +691,93 @@ describe('시간 조절·자리 비움·나가기 (§5.2, §8.5)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('시간 무제한 (§8.5)', () => {
|
||||
const U = { discussionPerAlive: null, voteSeconds: null, defenseSeconds: null, confirmSeconds: null, nightSeconds: null };
|
||||
const roles: Role[] = ['mafia', 'police', 'doctor', 'citizen', 'citizen'];
|
||||
const live = (s: MafiaState) => s.players.filter((p) => p.alive).map((p) => p.id);
|
||||
|
||||
test('모든 단계 무제한: 마감 없이 모두 마칠 때까지 기다리고, 기다리는 사람만 시간 초과 대상', () => {
|
||||
// Role reveal and greeting keep their fixed clocks.
|
||||
let s = until(busy(rig(roles, U)), 'night');
|
||||
expect(s.phase.kind === 'night' && s.phase.endsAt).toBeNull();
|
||||
expect(mafia.deadline!(s)).toBeNull();
|
||||
expect(mafia.timeoutNotBefore!(s)).toBeNull();
|
||||
expect(mafia.timeoutPlayers!(s)).toEqual(live(s));
|
||||
s = act(s, 'P0', { type: 'mafiaTarget', target: 'P3' });
|
||||
for (const p of ['P0', 'P1', 'P2', 'P3']) s = act(s, p, { type: 'readyEarly' });
|
||||
expect(reject(s, 'P0', { type: 'readyEarly' })).toBe('이미 밤 마치기를 눌렀어요.');
|
||||
expect(s.phase.kind).toBe('night');
|
||||
expect(mafia.view(s, 'P1').phase).toMatchObject({ readyCount: 4, readyNeeded: 5 });
|
||||
expect(mafia.timeoutPlayers!(s)).toEqual(['P4']);
|
||||
expect(reject(s, 'P1', { type: 'phaseTimeout' })).toBe('아직 기다리는 중이에요.');
|
||||
s = act(s, 'P4', { type: 'readyEarly' }, T0 + 3_600_000);
|
||||
expect(s.phase.kind).toBe('discussion');
|
||||
expect(pl(s, 'P3').alive).toBe(false);
|
||||
// Discussion: no ±15초; everybody alive presses 토론 끝내기.
|
||||
const v = mafia.view(s, 'P1');
|
||||
expect(v.phase.endsAt).toBeNull();
|
||||
expect(v.my!.canAdjust).toBe(false);
|
||||
expect(reject(s, 'P1', { type: 'adjustTime', delta: 15 })).toBe('이 방은 토론 시간이 무제한이에요.');
|
||||
for (const p of live(s)) s = act(s, p, { type: 'readyEarly' });
|
||||
expect(s.phase.kind).toBe('vote');
|
||||
// Vote: ends when every living player voted (abstain counts).
|
||||
s = act(s, 'P1', { type: 'vote', target: 'P0' });
|
||||
s = act(s, 'P2', { type: 'vote', target: 'P0' });
|
||||
s = act(s, 'P0', { type: 'vote', target: 'P1' });
|
||||
expect(mafia.view(s, null).phase).toMatchObject({ readyCount: 3, readyNeeded: 4 });
|
||||
s = act(s, 'P4', { type: 'vote', target: 'abstain' });
|
||||
expect(s.phase.kind === 'defense' && s.phase.accused).toBe('P0');
|
||||
// Defense: only the accused ends it.
|
||||
expect(reject(s, 'P1', { type: 'readyEarly' })).toBe('지목된 사람만 반론을 마칠 수 있어요.');
|
||||
expect(mafia.view(s, 'P0').my!.canReady).toBe(true);
|
||||
expect(mafia.timeoutPlayers!(s)).toEqual(['P0']);
|
||||
s = act(s, 'P0', { type: 'readyEarly' });
|
||||
expect(s.phase.kind).toBe('confirm');
|
||||
// Confirm: every voter but the accused.
|
||||
s = act(s, 'P1', { type: 'confirm', choice: 'yes' });
|
||||
s = act(s, 'P2', { type: 'confirm', choice: 'yes' });
|
||||
expect(s.phase.kind).toBe('confirm');
|
||||
s = act(s, 'P4', { type: 'confirm', choice: 'no' });
|
||||
expect(s.winner).toBe('town');
|
||||
});
|
||||
|
||||
test('자리 비운 사람은 방의 유예 시간 뒤 자기 차례만 넘김(기권·투표 없음·마침), 토론 시간만 무제한도 가능', () => {
|
||||
let s = until(busy(rig(roles, { voteSeconds: null, confirmSeconds: null })), 'vote');
|
||||
for (const p of ['P1', 'P2', 'P3']) s = act(s, p, { type: 'vote', target: 'P0' });
|
||||
s = act(s, 'P0', { type: 'vote', target: 'P1' });
|
||||
expect(mafia.timeoutPlayers!(s)).toEqual(['P4']);
|
||||
s = act(s, 'P4', mafia.onTimeout(s, 'P4'));
|
||||
expect(lastEv(s, 'vote')!.votes!.P4).toBe('abstain');
|
||||
// Defense keeps its 20 s clock (driver P0), then a 무제한 confirm.
|
||||
expect(s.phase.kind === 'defense' && s.phase.endsAt! - s.phase.startedAt).toBe(20_000);
|
||||
s = tick(s);
|
||||
expect(s.phase.kind).toBe('confirm');
|
||||
s = act(s, 'P1', { type: 'confirm', choice: 'no' });
|
||||
s = act(s, 'P2', { type: 'confirm', choice: 'no' });
|
||||
s = act(s, 'P3', mafia.onTimeout(s, 'P3'));
|
||||
expect(s.phase.kind).toBe('confirm');
|
||||
s = act(s, 'P4', mafia.onTimeout(s, 'P4'));
|
||||
expect(lastEv(s, 'confirm')).toMatchObject({ yes: 0, no: 2, outcome: 'spared' });
|
||||
expect(s.phase.kind).toBe('night');
|
||||
expect(s.phase.kind === 'night' && s.phase.endsAt! - s.phase.startedAt).toBe(30_000);
|
||||
// Only the discussion without a clock.
|
||||
let d = until(busy(until(rig(roles, { discussionPerAlive: null }), 'night')), 'discussion');
|
||||
expect(d.phase.kind === 'discussion' && d.phase.endsAt).toBeNull();
|
||||
for (const p of live(d).slice(1)) d = act(d, p, { type: 'readyEarly' });
|
||||
d = act(d, 'P0', mafia.onTimeout(d, 'P0'));
|
||||
expect(d.phase.kind === 'vote' && d.phase.endsAt! - d.phase.startedAt).toBe(20_000);
|
||||
});
|
||||
|
||||
test('무작위 대국(모든 단계 무제한)도 끝나고, 시간 초과 행동은 기다리는 사람에게 항상 합법', () => {
|
||||
for (let i = 1; i <= 120; i++) {
|
||||
const n = 4 + (i % 9);
|
||||
const options = { ...presetFor(i, n), ...U } as MafiaOptions;
|
||||
const a = fastPlayout(ids(n), options, seedN(9000 + i), 6000);
|
||||
if (!a.finished) throw new Error(`seed ${i} (${n} players) did not finish`);
|
||||
}
|
||||
}, 60_000);
|
||||
});
|
||||
|
||||
describe('스키마', () => {
|
||||
test('옵션에 한국어 메타, 기본값', () => {
|
||||
const shape = (mafia.optionsSchema as unknown as { shape: Record<string, { meta(): { title?: string } | undefined }> }).shape;
|
||||
@@ -783,7 +870,12 @@ function fastPlayout(players: PlayerId[], options: MafiaOptions, seed: RngState,
|
||||
const pool = pick < 2 ? players : mafia.activePlayers(s);
|
||||
actor = pool[chooser.int(pool.length)]!;
|
||||
const legal = mafia.legalActions!(s, actor);
|
||||
action = legal.length ? legal[chooser.int(legal.length)]! : mafia.onTimeout(s, actor);
|
||||
if (legal.length) action = legal[chooser.int(legal.length)]!;
|
||||
else {
|
||||
// Nothing to do (무제한: not awaited): the room's timeout for someone the phase waits on instead.
|
||||
actor = mafia.timeoutPlayers!(s)[0] ?? actor;
|
||||
action = mafia.onTimeout(s, actor);
|
||||
}
|
||||
}
|
||||
const v = mafia.validate(s, actor, action);
|
||||
if (!v.ok) throw new Error(`generated action rejected: ${v.reason} ${JSON.stringify(action)}`);
|
||||
@@ -858,8 +950,8 @@ describe(`무작위 대국 (시드 ${SEEDS}개, 4~12명)`, () => {
|
||||
while (!s.winner) {
|
||||
for (const p of [...s.players.map((x) => x.id)]) expect(mafia.validate(s, p, mafia.onTimeout(s, p)).ok).toBe(true);
|
||||
const ph = s.phase as Exclude<MafiaState['phase'], { kind: 'ended' }>;
|
||||
expect(mafia.validate(s, 'P0', mafia.onTimeout(s, 'P0'), { now: ph.endsAt }).ok).toBe(true);
|
||||
s = mafia.apply(s, 'P0', mafia.onTimeout(s, 'P0'), { rng: r, now: ph.endsAt }).state;
|
||||
expect(mafia.validate(s, 'P0', mafia.onTimeout(s, 'P0'), { now: ph.endsAt! }).ok).toBe(true);
|
||||
s = mafia.apply(s, 'P0', mafia.onTimeout(s, 'P0'), { rng: r, now: ph.endsAt! }).state;
|
||||
}
|
||||
// Only timeouts: nobody acts, so away eliminations end the game.
|
||||
expect(s.final!.cause === 'disconnect' || s.final!.cause === 'night').toBe(true);
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
import { z } from 'zod';
|
||||
import type { PlayerId } from '@bg/engine';
|
||||
|
||||
const lit = <T extends number>(...vals: T[]) =>
|
||||
const lit = <T extends number | null>(...vals: T[]) =>
|
||||
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
||||
const secLabels = (...vals: number[]) => Object.fromEntries(vals.map((v) => [v, `${v}초`]));
|
||||
/** Labels plus 무제한 (null): that phase has no clock and ends when everyone needed is done (§8.5). */
|
||||
const secLabelsU = (unl: string, ...vals: number[]) => ({ ...secLabels(...vals), null: unl });
|
||||
|
||||
export const ROLES = ['mafia', 'police', 'doctor', 'citizen', 'soldier', 'politician', 'medium', 'lover'] as const;
|
||||
export type Role = (typeof ROLES)[number];
|
||||
@@ -34,9 +36,10 @@ export const mafiaOptionsSchema = z.object({
|
||||
.enum(['day', 'night'])
|
||||
.default('day')
|
||||
.meta({ title: '시작 페이즈', labels: { day: '인사하는 낮부터(투표 없음)', night: '밤부터' } }),
|
||||
discussionPerAlive: lit(10, 15, 20)
|
||||
/** null = 무제한 토론: ends when every living player pressed 토론 끝내기 (min/max and ±15초 do not apply). */
|
||||
discussionPerAlive: lit<10 | 15 | 20 | null>(10, 15, 20, null)
|
||||
.default(15)
|
||||
.meta({ title: '토론 시간(살아 있는 사람 1명당)', labels: secLabels(10, 15, 20) }),
|
||||
.meta({ title: '토론 시간(살아 있는 사람 1명당)', labels: secLabelsU('무제한(모두 토론 끝내기를 누를 때까지)', 10, 15, 20) }),
|
||||
discussionMin: lit(30, 45, 60, 90, 120)
|
||||
.default(60)
|
||||
.meta({ title: '토론 시간 최소', labels: secLabels(30, 45, 60, 90, 120) }),
|
||||
@@ -44,18 +47,18 @@ export const mafiaOptionsSchema = z.object({
|
||||
.default(180)
|
||||
.meta({ title: '토론 시간 최대', labels: secLabels(60, 120, 180, 240, 300) }),
|
||||
timeAdjust: z.boolean().default(true).meta({ title: '하루 한 번 토론 시간 늘리기·줄이기(±15초)' }),
|
||||
voteSeconds: lit(10, 15, 20, 30, 45, 60)
|
||||
voteSeconds: lit<10 | 15 | 20 | 30 | 45 | 60 | null>(10, 15, 20, 30, 45, 60, null)
|
||||
.default(20)
|
||||
.meta({ title: '지목 투표 시간', labels: secLabels(10, 15, 20, 30, 45, 60) }),
|
||||
defenseSeconds: lit(10, 15, 20, 30, 45, 60)
|
||||
.meta({ title: '지목 투표 시간', labels: secLabelsU('무제한(모두 투표할 때까지)', 10, 15, 20, 30, 45, 60) }),
|
||||
defenseSeconds: lit<10 | 15 | 20 | 30 | 45 | 60 | null>(10, 15, 20, 30, 45, 60, null)
|
||||
.default(20)
|
||||
.meta({ title: '최후의 반론 시간', labels: secLabels(10, 15, 20, 30, 45, 60) }),
|
||||
confirmSeconds: lit(5, 10, 15, 20, 30)
|
||||
.meta({ title: '최후의 반론 시간', labels: secLabelsU('무제한(지목된 사람이 반론 마치기를 누를 때까지)', 10, 15, 20, 30, 45, 60) }),
|
||||
confirmSeconds: lit<5 | 10 | 15 | 20 | 30 | null>(5, 10, 15, 20, 30, null)
|
||||
.default(10)
|
||||
.meta({ title: '찬반 투표 시간', labels: secLabels(5, 10, 15, 20, 30) }),
|
||||
nightSeconds: lit(15, 20, 30, 45, 60, 90)
|
||||
.meta({ title: '찬반 투표 시간', labels: secLabelsU('무제한(모두 투표할 때까지)', 5, 10, 15, 20, 30) }),
|
||||
nightSeconds: lit<15 | 20 | 30 | 45 | 60 | 90 | null>(15, 20, 30, 45, 60, 90, null)
|
||||
.default(30)
|
||||
.meta({ title: '밤 시간', labels: secLabels(15, 20, 30, 45, 60, 90) }),
|
||||
.meta({ title: '밤 시간', labels: secLabelsU('무제한(모두 밤 마치기를 누를 때까지)', 15, 20, 30, 45, 60, 90) }),
|
||||
deathReveal: z
|
||||
.enum(['none', 'team', 'role'])
|
||||
.default('team')
|
||||
@@ -113,14 +116,18 @@ export interface PlayerState {
|
||||
export type Phase =
|
||||
| { kind: 'roleReveal'; startedAt: number; endsAt: number }
|
||||
| { kind: 'greeting'; startedAt: number; endsAt: number; ready: PlayerId[] }
|
||||
| { kind: 'discussion'; startedAt: number; endsAt: number; adjustedBy: PlayerId[]; ready: PlayerId[] }
|
||||
| { kind: 'vote'; startedAt: number; endsAt: number; votes: Record<PlayerId, PlayerId | 'abstain'> }
|
||||
| { kind: 'defense'; startedAt: number; endsAt: number; accused: PlayerId }
|
||||
| { kind: 'confirm'; startedAt: number; endsAt: number; accused: PlayerId; ballots: Record<PlayerId, 'yes' | 'no'> }
|
||||
// endsAt null = 무제한 (that phase's seconds option is null): it ends when everyone needed is done (§8.5).
|
||||
| { kind: 'discussion'; startedAt: number; endsAt: number | null; adjustedBy: PlayerId[]; ready: PlayerId[] }
|
||||
| { kind: 'vote'; startedAt: number; endsAt: number | null; votes: Record<PlayerId, PlayerId | 'abstain'> }
|
||||
| { kind: 'defense'; startedAt: number; endsAt: number | null; accused: PlayerId }
|
||||
/** `passed`: 무제한 only, voters the room moved on while away (no ballot). */
|
||||
| { kind: 'confirm'; startedAt: number; endsAt: number | null; accused: PlayerId; ballots: Record<PlayerId, 'yes' | 'no'>; passed?: PlayerId[] }
|
||||
| {
|
||||
kind: 'night';
|
||||
startedAt: number;
|
||||
endsAt: number;
|
||||
endsAt: number | null;
|
||||
/** 무제한 only: who pressed 밤 마치기 (everybody alive must, so it shows nothing about roles). */
|
||||
ready?: PlayerId[];
|
||||
mafiaTarget: PlayerId | null;
|
||||
mafiaPickedBy: PlayerId | null;
|
||||
investigate: PlayerId | null;
|
||||
@@ -270,6 +277,7 @@ export interface MafiaView {
|
||||
accused: PlayerId | null;
|
||||
/** Discussion: who used ±15초 today (public). */
|
||||
adjustedBy: PlayerId[];
|
||||
/** Greeting/discussion: 토론 끝내기; 무제한 vote/confirm/night: how many are done. */
|
||||
readyCount: number;
|
||||
readyNeeded: number;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user