병합: 루미큐브 앱 규칙 기본 + 끌어다 놓는 판(움직이는 동안 모두에게 보임)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-14 04:43:03 +09:00
13 changed files with 1587 additions and 534 deletions

View File

@@ -0,0 +1,142 @@
/**
* 루미큐브 through a real Room (docs/games/rummikub.md §5.6, §8.2–§8.3): the working table is broadcast to everybody
* on every drop, the drag preview goes out as a public `stream` message, and a v1 save is migrated on restore.
*/
import { describe, expect, test } from 'bun:test';
import type { ServerMessage } from '@bg/shared';
import { GAMES } from '@bg/games';
import { cellsOf, freeSpot, type RummikubState, type RummikubView } from '@bg/games/rummikub';
import { openDb } from '../db';
import { TokenBucket } from '../ws/rate-limit';
import { Room, type Conn, type RoomConfig, type RoomSnapshot } from './room';
import { RoomStore } from './store';
type Msgs = ServerMessage[];
type StateMsg = Extract<ServerMessage, { t: 'state' }>;
function harness() {
const db = openDb(':memory:');
const store = new RoomStore(db);
let now = 1_000_000;
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
const games = { rummikub: GAMES.rummikub! };
const deps = { store, games, users: { publicUser: (id: string) => ({ id, nickname: id, avatar: null, kind: 'guest' as const }) }, now: clock.now };
const config: RoomConfig = {
gameId: 'rummikub',
options: { ...games.rummikub.defaultOptions },
maxPlayers: 2,
visibility: 'private',
allowSpectators: true,
chatEnabled: true,
chatFilter: true,
graceSec: 60,
};
const room = new Room('room1', '482913', config, 'A', deps);
store.insertRoom({ id: 'room1', code: '482913', hostId: 'A', gameId: 'rummikub', status: 'lobby', visibility: 'private', config, stateJson: '{}', now });
const conn = (p: string) => {
const msgs: Msgs = [];
const c: Conn & { msgs: Msgs } = { userId: p, msgs, send: (m) => msgs.push(m), close: () => {} };
return c;
};
const conns: Record<string, Conn & { msgs: Msgs }> = { A: conn('A'), B: conn('B') };
room.join(conns.A!, 'player');
room.join(conns.B!, 'player');
expect(room.start('A')).toBeNull();
room.clearTimer();
conns.S = conn('S');
room.join(conns.S, 'spectator');
const state = () => room.game!.state as RummikubState;
let cs = 100;
const act = (p: string, a: unknown) => {
room.act(p, ++cs, a);
room.clearTimer();
return cs;
};
return { room, store, deps, clock, conns, state, act };
}
const lastView = (m: Msgs) => (m.filter((x): x is StateMsg => x.t === 'state').at(-1)!.view as RummikubView);
describe('루미큐브 room flow', () => {
test('놓을 때마다 바닥이 모두(상대·관전자)에게 바로 보이고, 받침대의 나머지 타일은 보이지 않음', () => {
const { conns, state, act } = harness();
const cur = state().current;
const other = cur === 'A' ? 'B' : 'A';
const [t1, t2, ...rest] = state().racks[cur]! as [string, string, ...string[]];
act(cur, { type: 'arrange', cells: [{ id: t1, r: 1, c: 2 }], turn: state().turnNo });
for (const who of [other, 'S']) {
const v = lastView(conns[who]!.msgs);
expect(v.draft!.cells).toEqual([{ id: t1, r: 1, c: 2 }]);
expect(v.draftEdits).toBe(1);
const json = JSON.stringify(v);
for (const id of [t2, ...rest]) expect(json.includes(`"${id}"`)).toBe(false);
}
// Moving it again: everybody sees the new place.
act(cur, { type: 'arrange', cells: [{ id: t1, r: 3, c: 7 }, { id: t2, r: 3, c: 8 }], turn: state().turnNo });
expect(lastView(conns[other]!.msgs).draft!.cells).toEqual([
{ id: t1, r: 3, c: 7 },
{ id: t2, r: 3, c: 8 },
]);
// 되돌리기: back to the turn start for everybody.
act(cur, { type: 'resetDraft' });
expect(lastView(conns.S!.msgs).draft!.cells).toEqual([]);
});
test('끄는 중인 타일은 stream 메시지로만 중계되고(전체 view 재전송 없음), 받침대 타일은 뒷면(null)', () => {
const { conns, state, act } = harness();
const cur = state().current;
const other = cur === 'A' ? 'B' : 'A';
const [t1, t2] = state().racks[cur]! as [string, string];
act(cur, { type: 'arrange', cells: [{ id: t1, r: 0, c: 0 }], turn: state().turnNo });
const before = { o: conns[other]!.msgs.length, s: conns.S!.msgs.length, me: conns[cur]!.msgs.length };
const mine = act(cur, { type: 'drag', ids: [t1, t2], x: 4.5, y: 2, turn: state().turnNo });
for (const [who, n] of [
[other, before.o],
['S', before.s],
] as const) {
const got = conns[who]!.msgs.slice(n);
expect(got).toEqual([{ t: 'stream', seq: expect.any(Number), events: [{ type: 'drag', player: cur, turn: state().turnNo, tiles: [t1, null], x: 4.5, y: 2 }] }]);
}
// The sender gets the same stream message with its cs (no `pending` lock, no reject).
expect(conns[cur]!.msgs.slice(before.me)).toEqual([{ t: 'stream', seq: expect.any(Number), events: expect.any(Array), cs: mine }]);
// A late drag from the other player is dropped silently: no error, nothing relayed.
const n = conns[other]!.msgs.length;
act(other, { type: 'drag', ids: [], x: 0, y: 0 });
expect(conns[other]!.msgs.slice(n).some((m) => m.t === 'reject')).toBe(false);
});
test('drag preview pace (5/s) + drops stay well under the socket token bucket (20/s, burst 40)', () => {
const bucket = new TokenBucket(20, 40, 0);
let dropped = 0;
// 30 seconds of non-stop dragging: a preview every 200 ms and a drop every second.
for (let t = 0; t < 30_000; t += 200) {
if (!bucket.take(t)) dropped++;
if (t % 1000 === 0 && !bucket.take(t)) dropped++;
}
expect(dropped).toBe(0);
});
test('예전 저장(v1, 칸 위치 없음)을 불러오면 칸 판으로 바뀌고 이어서 둘 수 있음', () => {
const { room, store, deps, state, act } = harness();
act(state().current, { type: 'draw' });
room.clearTimer();
const { seq, stateJson } = store.openRooms()[0]!;
const snap = JSON.parse(stateJson) as RoomSnapshot;
const g = snap.game!.state as Record<string, any>;
// What a v1 save looked like: sets without places, a draft of sets with an undo history.
g.table = [];
g.draft = { sets: [], history: [], edits: 0 };
snap.game!.stateVersion = 1;
const restored = Room.restore('room1', '482913', seq, snap, deps);
restored.clearTimer();
const s = restored.game!.state as RummikubState;
expect(restored.game!.stateVersion).toBe(2);
expect(s.draft).toEqual({ cells: [], edits: 0 });
const p = s.current;
const id = s.racks[p]![0]!;
const spot = freeSpot(cellsOf(s.table), 1)!;
restored.act(p, 1, { type: 'arrange', cells: [{ id, ...spot }] });
restored.clearTimer();
expect((restored.game!.state as RummikubState).draft.cells).toEqual([{ id, ...spot }]);
});
});

View File

@@ -6,6 +6,8 @@ import { helpNow } from './help';
const users = usersOf(['A', 'B', 'C']);
const view = (s: unknown, who: string | null) => GAMES.rummikub!.view(s, who) as any;
const nickOf = (id: string) => `${users[id]!.nickname}님`;
/** Tiles side by side in the top row = one set on the grid. */
const row = (ids: string[]) => ids.map((id, c) => ({ id, r: 0, c }));
/** Fresh game; the current player gets a known rack (view-only edit, enough for help text). */
function game(options: Record<string, unknown> = {}, rack?: string[]) {
@@ -39,34 +41,36 @@ test('루미큐브: 방 옵션 반영(첫 등록 없음, 힌트 끔)', () => {
const t = helpNow(view(state, cur), cur, users);
expect(t).not.toContain('첫 등록');
expect(t).not.toContain('[도와줘]');
expect(t).toContain('바닥 묶음을 쪼개고 합쳐');
expect(t).toContain('묶음을 쪼개고 합쳐');
});
test('루미큐브: 틀린 배치 / 올바른 배치 / 조커', () => {
const rack = ['R10a', 'R11a', 'R12a', 'K1a', 'JK1'];
const { state, cur } = game({}, rack);
const bad = applyAction('rummikub', state, cur, { type: 'setDraft', sets: [{ tileIds: ['K1a'] }] });
const { state, cur, other } = game({}, rack);
const bad = applyAction('rummikub', state, cur, { type: 'arrange', cells: [{ id: 'K1a', r: 0, c: 0 }] });
const tb = helpNow(view(bad, cur), cur, users);
expect(tb).toContain('아직 확정할 수 없어요');
expect(tb).toContain('아직 완료할 수 없어요');
expect(tb).toContain('[되돌리기]');
expect(tb).toContain('3장을 가져와요');
expect(tb).toContain('1장을 가져와요');
expect(tb).toContain('조커');
const good = applyAction('rummikub', state, cur, { type: 'setDraft', sets: [{ tileIds: ['R10a', 'R11a', 'R12a'] }] });
// The others see the tile being moved.
expect(helpNow(view(bad, other), other, users)).toContain('옮기는 타일이 바로 보여요');
const good = applyAction('rummikub', state, cur, { type: 'arrange', cells: row(['R10a', 'R11a', 'R12a']) });
const tg = helpNow(view(good, cur), cur, users);
expect(tg).toContain('(지금 33점)');
expect(tg).toContain('[확정]을 눌러야');
expect(tg).toContain('[완료]를 눌러야');
const p3 = game({ invalidCommitPenalty: 'penalty3', invalidTimeoutPenalty: 1 }, rack);
const bad3 = applyAction('rummikub', p3.state, p3.cur, { type: 'setDraft', sets: [{ tileIds: ['K1a'] }] });
const p3 = game({ invalidCommitPenalty: 'penalty3', invalidTimeoutPenalty: 3 }, rack);
const bad3 = applyAction('rummikub', p3.state, p3.cur, { type: 'arrange', cells: [{ id: 'K1a', r: 0, c: 0 }] });
const t3 = helpNow(view(bad3, p3.cur), p3.cur, users);
expect(t3).toContain('틀린 채로 [확정]하면');
expect(t3).toContain('1장을 가져와요');
expect(t3).toContain('틀린 채로 [완료]하면');
expect(t3).toContain('3장을 가져와요');
});
test('루미큐브: 판 끝(다음 판 시작) / 게임 끝', () => {
const rack = ['R10a', 'R11a', 'R12a'];
const m = game({ gamesPerMatch: '2' }, rack);
let s = applyAction('rummikub', m.state, m.cur, { type: 'setDraft', sets: [{ tileIds: rack }] });
let s = applyAction('rummikub', m.state, m.cur, { type: 'arrange', cells: row(rack) });
s = applyAction('rummikub', s, m.cur, { type: 'commit' });
expect(s.phase).toBe('roundEnd');
const t = helpNow(view(s, m.other), m.other, users);
@@ -78,7 +82,7 @@ test('루미큐브: 판 끝(다음 판 시작) / 게임 끝', () => {
expect(helpNow(view(s2, null), null, users)).toContain('기다리는 중');
const one = game({}, rack);
let f = applyAction('rummikub', one.state, one.cur, { type: 'setDraft', sets: [{ tileIds: rack }] });
let f = applyAction('rummikub', one.state, one.cur, { type: 'arrange', cells: row(rack) });
f = applyAction('rummikub', f, one.cur, { type: 'commit' });
expect(f.phase).toBe('finished');
expect(helpNow(view(f, one.other), one.other, users)).toContain('게임이 끝났어요');

View File

@@ -54,7 +54,7 @@ export function helpNow(v: RummikubView, me: string | null, players: Record<stri
if (!seat || !my) {
const lines = [`${curName} 차례예요${curSeat ? `(받침대 ${curSeat.tiles}장)` : ''}. ${pool}`];
if (curSeat && !curSeat.melded) lines.push(`${curName}은 아직 첫 등록 전이라 받침대 타일만으로 ${v.options.initialMeldPoints}점 이상을 만들어 내야 해요.`);
if (v.draft) lines.push(`바닥에는 ${curName}이 고민 중인 배치가 보여요. [확정] 전이라 바뀔 수 있어요.`);
if (v.draft && v.draftEdits > 0) lines.push(`바닥에서 ${curName}이 타일을 옮기는 모습이 그대로 보여요. [완료] 전이라 바뀔 수 있어요.`);
else if (v.draftEdits > 0) lines.push(`${curName}이 타일을 옮겨 보며 생각 중이에요.`);
if (curSeat?.away) lines.push(`${curName}은 자리 비움 상태라 차례가 금방 넘어가요.`);
lines.push('같은 숫자 다른 색 3~4장, 또는 같은 색 이어진 숫자 3장 이상으로 묶어 받침대를 먼저 비우면 이겨요.');
@@ -69,7 +69,8 @@ export function helpNow(v: RummikubView, me: string | null, players: Record<stri
: '';
if (cur !== me) {
const lines = [`${curName} 차례예요. 기다려 주세요.${v.draft ? ` 바닥에 ${curName}이 고민 중인 배치가 보여요(확정 전).` : v.draftEdits > 0 ? ` ${curName}이 생각 중이에요.` : ''}`];
const moving = v.draftEdits > 0 ? (v.draft ? ` 바닥에서 ${curName}이 옮기는 타일이 바로 보여요([완료] 전).` : ` ${curName}이 생각 중이에요.`) : '';
const lines = [`${curName} 차례예요. 기다려 주세요.${moving}`];
lines.push(`내 받침대 ${my.rack.length}장 · ${pool}`);
if (!my.melded) lines.push(`나는 아직 첫 등록 전이에요. ${meldRule(v)}`);
if (seat.away) lines.push('시간 초과가 이어져 자리 비움 상태예요. 내 차례가 3초 만에 넘어가니, 차례가 오면 바로 무엇이든 해 주세요.');
@@ -81,20 +82,22 @@ export function helpNow(v: RummikubView, me: string | null, players: Record<stri
// My turn.
const check = my.check;
const drawLabel = v.poolCount > 0 ? '[한 장 가져오기]' : '[넘기기]';
const lines = [`내 차례예요(받침대 ${my.rack.length}장). 타일을 눌러 고른 뒤, 바닥 묶음의 ◀ 앞·▶ 뒤나 [새 묶음]을 눌러 놓아요.`];
const lines = [
`내 차례예요(받침대 ${my.rack.length}장). 받침대의 타일을 바닥으로 끌어다 놓아요. 한 줄에 나란히 붙은 타일이 한 묶음이고, 한 칸 띄우면 다른 묶음이에요. 눌러서 고른 뒤 빈 칸이나 [새 묶음]을 눌러도 돼요.`,
];
if (!my.melded) lines.push(meldRule(v, check?.meldPoints ?? 0));
else lines.push('바닥 묶음을 쪼개고 합쳐 내 타일을 끼워 넣어도 돼요. 바닥 타일은 받침대로 가져올 수 없어요.');
else lines.push('바닥 타일도 끌어서 묶음을 쪼개고 합쳐 내 타일을 끼워 넣어도 돼요. 타일 위에 놓으면 오른쪽이 밀리며 사이에 들어가요. 바닥 타일은 받침대로 가져올 수 없어요.');
if (!my.changed) {
const hint = v.options.hints ? ' [도와줘]를 누르면 받침대 타일로 바로 낼 수 있는 묶음을 보라색으로 찾아 줘요.' : '';
lines.push(`낼 게 없으면 ${drawLabel}를 눌러요. 그러면 차례가 끝나요.${hint} ${pool}`);
} else if (check?.ok) {
lines.push(`바닥이 모두 올바라요. [확정]을 눌러야 차례가 끝나요.${v.options.timeoutValidDraft === 'revert' ? ' 시간이 다 되면 놓은 타일이 돌아오고 1장을 가져오니 서둘러요.' : ''}`);
lines.push(`바닥이 모두 올바라요. [완료]를 눌러야 차례가 끝나요.${v.options.timeoutValidDraft === 'revert' ? ' 시간이 다 되면 놓은 타일이 돌아오고 1장을 가져오니 서둘러요.' : ''}`);
} else {
lines.push(`아직 확정할 수 없어요: ${check?.reason ?? '바닥 묶음을 확인해 주세요.'} 고치기 어려우면 [되돌리기](한 단계 전)나 [처음으로](차례 시작 상태)를 눌러요.`);
lines.push(`아직 완료할 수 없어요: ${check?.reason ?? '바닥 묶음을 확인해 주세요.'} 빨간 테두리 묶음을 고치거나, 어려우면 [되돌리기]로 차례 시작 상태로 돌려요.`);
lines.push(
v.options.invalidCommitPenalty === 'penalty3'
? `이 방에서는 틀린 채로 [확정]하면 놓은 타일이 돌아오고 3장을 가져와요. 시간이 다 돼도 처음으로 돌아가고 ${v.options.invalidTimeoutPenalty}장을 가져와요.`
? `이 방에서는 틀린 채로 [완료]하면 놓은 타일이 돌아오고 3장을 가져와요. 시간이 다 돼도 처음으로 돌아가고 ${v.options.invalidTimeoutPenalty}장을 가져와요.`
: `틀린 채로 시간이 다 되면 처음으로 돌아가고 ${v.options.invalidTimeoutPenalty}장을 가져와요. ${drawLabel}를 누르면 확인 창이 뜨고, 바꾼 배치를 되돌린 뒤 차례를 끝내요.`,
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -63,13 +63,16 @@ export const quickStart: QuickCard[] = [
{row(5, 30, [['K', 7], ['R', 7], ['B', 7]])}
{label(185, 22, '이어진 숫자')}
{row(126, 30, [['B', 3], ['B', 4], ['B', 5], ['B', 6]])}
<rect x={20} y={88} width={210} height={52} rx={8} fill="#b07a3c" />
{row(35, 94, [['O', 2], ['K', 9], ['R', 12], ['J', 0], ['B', 1], ['O', 13]])}
<text x={125} y={84} textAnchor="middle" fontSize={11} fontWeight={800} fill="#fde047">
▲ 받침대에서 끌어다 놓기
</text>
<rect x={20} y={92} width={210} height={52} rx={8} fill="#b07a3c" />
{row(35, 98, [['O', 2], ['K', 9], ['R', 12], ['J', 0], ['B', 1], ['O', 13]])}
</Felt>
),
alt: '바닥에 같은 숫자 7 세 장과 파란 3·4·5·6이 놓여 있고, 아래 받침대에 내 타일이 있어요',
title: '묶음을 만들어 내요',
text: '같은 숫자 다른 색 3~4장, 또는 같은 색 이어진 숫자 3장 이상을 바닥에 내요. 낼 게 없으면 한 장 가져와요.',
alt: '바닥에 같은 숫자 7 세 장과 파란 3·4·5·6이 놓여 있고, 아래 받침대의 타일을 바닥으로 끌어다 놓아요',
title: '끌어다 놓아 묶음을 만들어요',
text: '받침대의 타일을 바닥으로 끌어다 놓아요. 나란히 붙은 타일이 한 묶음이에요. 같은 숫자 다른 색 3~4장, 또는 같은 색 이어진 숫자 3장 이상이면 [완료]. 낼 게 없으면 한 장 가져와요.',
},
{
pic: (
@@ -96,6 +99,6 @@ export const quickStart: QuickCard[] = [
),
alt: '빨간 4부터 8까지 묶음에 내 빨강 6을 넣어 4·5·6과 6·7·8 두 묶음으로 나눈 모습',
title: '바닥을 고쳐서 끼워요',
text: '첫 등록 뒤에는 바닥 묶음을 쪼개고 합쳐 내 타일을 끼울 수 있어요. 조커는 아무 타일이나 대신해요. 받침대를 먼저 비우면 이겨요.',
text: '첫 등록 뒤에는 바닥 타일도 끌어서 묶음을 쪼개고 합쳐 내 타일을 끼울 수 있어요. 시간 안에 [완료]하지 못하면 바닥이 처음으로 돌아가고 한 장 가져와요. 받침대를 먼저 비우면 이겨요.',
},
];