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

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: '첫 등록 뒤에는 바닥 타일도 끌어서 묶음을 쪼개고 합쳐 내 타일을 끼울 수 있어요. 시간 안에 [완료]하지 못하면 바닥이 처음으로 돌아가고 한 장 가져와요. 받침대를 먼저 비우면 이겨요.',
},
];

View File

@@ -26,6 +26,7 @@
## 0-3. 확정된 결정 (2026-10-14)
- 게임 속도: 전체가 빠르다는 요청으로 1배에서도 애니메이션·연출과 컴퓨터 생각 시간을 예전의 1.5배로 늘렸다. 관리자 사이트 설정 "게임 속도 배율"(1/16~16배, 기본 1배)로 둘 다 나눠서 조절하고, 저장하면 열린 방에도 바로 적용한다. 턴 제한 시간·결과 화면 대기 같은 규칙 시간과 반응 경쟁(원카드 외치기, 할리갈리·도블 판정)은 공정성 때문에 배율과 무관하다.
- 루미큐브: 사용자 요청("루미큐브 앱 규칙으로", "드래그해서 화면에 놔두고 합치는 방식, 모두한테 보이게")으로 루미큐브 앱(Rummikub® 공식 앱) 방식을 기본으로 바꿨다. ① 바닥은 칸(20×12) 판이고, 받침대·바닥의 타일을 끌어다 아무 칸에나 놓으며 한 줄에 나란히 붙은 타일이 한 묶음이다(눌러 고르고 빈 칸 누르기도 됨). ② 차례인 사람이 옮기는 바닥은 모두(관전자 포함)에게 바로 보이고, 끄는 중인 타일도 초당 5번 미리 보기로 보인다(받침대에서 아직 안 내려놓은 타일은 뒷면). ③ [되돌리기]는 한 단계가 아니라 차례 시작 상태로 통째로 돌린다(앱의 Undo). ④ 시간이 다 되면 [완료]를 안 누른 배치는 올발라도 처음으로 돌아가고 1장을 가져온다(앱: 리뷰 "your entire turn is reset and you are penalized another tile"). 종이 규칙서의 "미완성 3장"·"자동 완료"는 옵션으로 남김. ⑤ 한 차례 시간에 앱의 30초를 더함(기본 1분 유지). 106장·14장·첫 등록 30점(받침대 타일만)·조커 회수 뒤 같은 차례 재사용·첫 등록 전 조커 회수 불가·풀 소진 뒤 아무도 못 내면 끝·점수 계산은 그대로(종이 규칙서와 같음). 근거: 공식 규칙서 https://rummikub.com/wp-content/uploads/2019/12/2600-English-1.pdf , 앱 설명 https://apps.apple.com/us/app/rummikub/id1015322991 , 앱 리뷰 https://apps.apple.com/us/app/rummikub/id973113361?see-all=reviews&platform=iphone , 앱 사용자 정리 https://game-solver.com/rummikub-2/ (자세히: `games/rummikub.md` §2, §5.6~§5.7, §13).
## 1. 운영 (진행에 꼭 필요)
| # | 항목 | 기본안 | 필요한 것 |
@@ -61,6 +62,7 @@
| 도둑잡기 (2026-10-12) | 조커 1장, 짝은 자동으로 버림, 한 번 뽑기 20초 | 10·30·60초 |
| 우노 (2026-10-12) | 공식 규칙(한 판 점수, 와일드 드로우4 도전) | 500점 먼저, 쉬운 드로우4, 드로우 쌓기·낼 때까지 뽑기(하우스 룰) |
| 라이어 게임 (2026-10-12) | 라이어 1명, 설명 1바퀴, 동점은 한 번 더 투표 후 또 동점이면 라이어 승, 정답은 직접 적기 | 주제, 바보 모드, 2바퀴, 목록에서 고르기, 단계별 시간 |
| 루미큐브 (2026-10-14) | 루미큐브 앱 방식: 칸 판에 끌어다 놓기, 옮기는 타일 모두에게 보이기, 되돌리기 = 차례 처음으로, 시간 초과는 무조건 되돌리고 1장, 틀린 완료는 알려 주고 계속 | 종이 규칙서(시간 초과 3장·올바른 배치 자동 완료), 옮기는 타일 비공개, 인원수만큼 판, 첫 등록 0·20·50점, 조커 50점 |
| 야단법석 달리기 (2026-10-13) | 4~6명은 선수 4명(경주마다 1명), 2~3명은 8명(둘씩), 경주 4번·1등 3점 2등 1점, 원작 선수 36명 중 24명 | 순한 판·거친 판, 뒤로 갈수록 커지는 점수표 |
## 게임 그림 출처 (2026-10-13)

View File

@@ -8,17 +8,19 @@
- 인원 근거: 공식 규칙서 기본판 106타일은 2~4명이다. 5~6명은 160타일 확장판(XP)용이라 범위에서 뺀다.
## 2. 모드와 옵션
기본값은 **루미큐브 앱**(Rummikub® 공식 앱) 방식이다(2026-10-14, §13). 종이 규칙서와 다른 점은 옵션으로 고를 수 있다.
| 옵션 키 | 설명 | 선택지 | 기본값 |
|---|---|---|---|
| `initialMeldPoints` | 첫 등록에 필요한 최소 점수 | 0(없음) / 20 / 30 / 50 | 30 |
| `turnSeconds` | 턴 제한 시간(공식 1분) | 60 / 90 / 120 / 180 / null(무제한) | 60 |
| `timeoutValidDraft` | 시간 초과 때 초안이 유효한 경우 처리 | `commit`(자동 확정) / `revert`(공식대로 되돌리고 1장 뽑기) | `commit` |
| `invalidTimeoutPenalty` | 시간 초과 때 초안이 무효한 경우 뽑는 장수(공식 3) | 1 / 3 | 3 |
| `invalidCommitPenalty` | "완료"를 눌렀는데 무효일 때 처리 | `reject`(거부만, 계속 수정) / `penalty3`(되돌리고 3장 뽑고 턴 종료) | `reject` |
| `turnSeconds` | 턴 제한 시간(공식 1분, 앱은 15초·30초·1분·2분) | 30 / 60 / 90 / 120 / 180 / null(무제한) | 60 |
| `timeoutValidDraft` | 시간 초과 때 작업 중인 바닥이 올바른 경우 | `revert`(앱·규칙서: 되돌리고 1장) / `commit`(자동 완료) | `revert` |
| `invalidTimeoutPenalty` | 시간 초과 때 바닥이 틀린 경우 가져오는 장수 | 1(앱) / 3(종이 규칙서) | 1 |
| `invalidCommitPenalty` | "완료"를 눌렀는데 틀렸을 때 | `reject`(앱: 알려 주고 계속 고치기) / `penalty3`(되돌리고 3장 뽑고 턴 종료) | `reject` |
| `jokerPenalty` | 랙에 남은 조커 감점 | 30(공식) / 50(대회) | 30 |
| `initialMeldAllowExtend` | 첫 등록 턴에 기존 테이블 세트에도 붙이기 허용 | on / off(공식) | off |
| `showDraftToOthers` | 내가 고민 중인 초안을 다른 사람에게 실시간으로 보이기 | on / off | off |
| `gamesPerMatch` | 한 매치의 판 수(공식은 인원수만큼 판 = 1라운드) | 1 / 인원수 / 2 / 3 / 4 | 1 |
| `showDraftToOthers` | 차례인 사람이 옮기는 바닥(끄는 중인 타일 포함)을 모두에게 실시간으로 보이기 | on(앱) / off | on |
| `gamesPerMatch` | 한 매치의 판 수(앱은 1판, 종이 규칙서는 인원수만큼 판 = 1라운드) | 1 / 인원수 / 2 / 3 / 4 | 1 |
| `hints` | "낼 수 있는 조합 찾기" 힌트 버튼 | on / off | on |
## 3. 구성물
@@ -72,25 +74,29 @@
- 3개짜리 그룹의 조커: 빠진 두 색 중 아무 색으로 바꿔도 된다.
- 회수한 조커는 같은 턴에 테이블에 다시 써야 하고, 랙으로 가져갈 수 없다. 이번 턴에 랙에서 최소 1개를 내야 하는 조건도 그대로다.
- 첫 등록 전에는 조커를 회수할 수 없다(첫 등록 전에는 재배치 자체가 불가).
- 엔진 구현 원칙: 조커 회수를 따로 액션으로 두지 않는다. "턴 종료 시점의 테이블 전체가 유효하고, 테이블 타일 집합 ⊇ 턴 시작 시점 테이블 타일 집합"만 검사하면 위 조건이 모두 자동으로 지켜진다. 조커가 다른 세트로 옮겨 가도 되고, 런 끝 조커를 떼어 새 세트에 써도 된다(공식 예시 3·4번과 같음).
- 엔진 구현 원칙: 조커 회수를 따로 액션으로 두지 않는다(앱에서도 조커를 다른 타일처럼 끌어 옮긴다). "턴 종료 시점의 테이블 전체가 유효하고, 테이블 타일 집합 ⊇ 턴 시작 시점 테이블 타일 집합"만 검사하면 위 조건이 모두 자동으로 지켜진다. 조커가 다른 세트로 옮겨 가도 되고, 런 끝 조커를 떼어 새 세트에 써도 된다(공식 예시 3·4번과 같음).
- 단순화 메모: 공식 문구는 "회수한 조커는 새 세트를 만드는 데 써야 한다"이지만, 조커를 기존 세트로 옮기는 것도 허용한다. 엄격히 하려면 "턴 시작 때 테이블에 있던 조커는 턴 시작 때와 같은 세트 구성원 집합에 머물 수 없다" 같은 검사가 필요하지만, 실제 대국에서 차이가 거의 없어 기본은 생략한다.
- **조커 값 해석**(점수·표시용): 서버가 각 세트를 정규화할 때 조커의 색·숫자를 정한다.
- 런: 클라이언트가 보낸 순서 그대로 유효하면 그 순서를 따른다. 아니면 정렬한 뒤 빈칸을 조커로 채우고, 남는 조커는 위쪽 끝(13 방향)에 먼저 붙이고 불가능하면 아래쪽 끝에 붙인다.
- 그룹: 숫자는 그룹의 숫자이고 색은 "빠진 색 중 하나"로 표시한다(정해지지 않음).
- 런과 그룹 둘 다 될 수 있는 세트(예: [빨강5, 조커, 조커])는 클라이언트의 `as` 힌트를 따르고, 힌트가 없으면 런으로 해석한다.
### 5.6 초안(draft)과 되돌리기
- 내 턴 동안 테이블을 바꾸는 것은 서버에 있는 "초안"을 바꾸는 것이다. 초안은 턴을 확정하기 전까지 실제 테이블이 아니다.
- "되돌리기"는 초안을 바로 이전 단계로, "처음으로"는 턴 시작 상태로 돌린다. 서버가 초안 기록(최대 100단계)을 보관하므로 재접속해도 유지된다.
- 초안 중간 상태는 무효해도 된다(낱개 타일, 2개짜리 세트 등). 검증은 "완료"를 누를 때와 시간 초과 때만 한다.
### 5.6 칸 판, 작업 중인 바닥(draft)과 되돌리기 (2026-10-14, 앱 방식)
- 바닥은 앱처럼 **칸 판**(가로 20 × 세로 12칸)이다. 타일은 칸 하나에 하나씩 놓이고, **한 줄에 빈칸 없이 나란히 붙은 타일이 한 묶음**이다. 빈칸 하나가 묶음을 나눈다. 묶음 안의 순서는 왼쪽→오른쪽이고, 조커 해석(§5.5)도 이 순서를 따른다. 20 × 12면 어떤 바닥(106장 + 묶음 사이 빈칸, 13장 런 한 줄)도 들어간다.
- 타일 위에 놓으면 그 칸부터 그 줄 오른쪽 타일이 놓는 장수만큼 밀려 사이에 끼워진다(줄 끝을 넘으면 놓을 수 없음). 빈 칸에 놓으면 그 자리에 놓이고, 묶음 바로 옆 칸이면 그 묶음에 붙는다.
- 내 턴 동안 바닥을 바꾸는 것은 서버에 있는 "작업 중인 바닥"(칸 목록)을 바꾸는 것이다. 손을 놓을(drop) 때마다 바닥 전체를 보낸다(`arrange`). [완료]를 누르기 전까지 실제 테이블이 아니다.
- 작업 중에는 틀려도 된다(낱개 타일, 2장 묶음, 바닥 묶음 옆에 붙인 타일 등). 검증은 [완료]와 시간 초과 때만 한다. 화면은 놓을 때마다 각 묶음을 초록(새로 만들거나 바뀐 올바른 묶음)·빨강 점선(틀림, 이유 표시)으로 보여 준다.
- **[되돌리기]**는 앱처럼 한 단계가 아니라 **차례 시작 상태로 통째로** 돌린다(앱 사용자 정리: "There are no incremental undos ... it removes everything you did!"). 그래서 단계 기록(history)을 저장하지 않는다(놓을 때마다 스냅숏이 커지지 않게).
- 재접속해도 작업 중인 바닥은 서버에 남는다.
- 예전 저장(stateVersion 1: 칸 위치 없는 묶음 목록)은 서버가 불러올 때 `migrate`가 바닥 묶음과 작업 중인 묶음에 칸 위치를 붙인다(되돌리기 기록은 버림). 규칙이 바뀌었으므로 v1 게임의 다시 보기는 열리지 않는다(기존 정책).
### 5.7 시간 제한과 벌칙(공식 + 옵션)
### 5.7 시간 제한과 벌칙(앱 기본 + 옵션)
- 턴 제한은 `turnSeconds`(공식 1분)다.
- 시간 초과 때
- 초안이 턴 시작과 같으면 1개를 뽑고 턴이 끝난다(풀이 비었으면 넘기기).
- 초안이 유효하고 랙 타일이 1개 이상 들어 있으면 `timeoutValidDraft = commit`일 때 자동으로 확정한다. `revert`면 되돌리고 1개를 뽑는다.
- 초안이 무효하면 테이블을 턴 시작 상태로 되돌리고, 낸 타일은 랙으로 돌아오며, `invalidTimeoutPenalty`(공식 3)개를 뽑고 턴이 끝난다.
- "완료"를 눌렀는데 무효하면 `invalidCommitPenalty = reject`(기본)일 때 거부만 하고, 무효한 세트를 빨간색으로 표시한 뒤 계속 고칠 수 있게 한다. 타이머는 계속 간다.
- 시간 초과 때(앱 기본: [완료]를 누르지 않은 배치는 무조건 처음으로)
- 바닥이 턴 시작과 같은 묶음이면(자리만 옮긴 것 포함) 1개를 뽑고 턴이 끝난다(풀이 비었으면 넘기기).
- 바닥이 올바르고 랙 타일이 1개 이상 들어 있어도 기본(`timeoutValidDraft = revert`)은 바닥을 되돌리고 1개를 뽑는다. 앱 리뷰: "even if you've already completed an earlier legal move, your entire turn is reset and you are penalized another tile". `commit`이면 자동으로 완료한다.
- 바닥이 틀리면 턴 시작 상태로 되돌리고, 낸 타일은 랙으로 돌아오며, `invalidTimeoutPenalty`(기본 1 = 앱, 종이 규칙서 3)개를 뽑고 턴이 끝난다. 1장이면 기록은 "시간 초과", 3장이면 "벌칙"으로 보인다.
- "완료"를 눌렀는데 틀리면 `invalidCommitPenalty = reject`(기본)일 때 거부만 하고, 틀린 묶음을 빨간색으로 표시한 뒤 계속 고칠 수 있게 한다. 타이머는 계속 간다.
### 5.8 풀이 다 떨어졌을 때(공식)
- 풀이 비어도 누군가 랙을 다 비우거나 더 이상 아무도 낼 수 없을 때까지 계속한다.
@@ -131,9 +137,10 @@ interface TableSet {
tileIds: string[]; // 정규화된 순서(런은 오름차순)
kind: 'run' | 'group';
jokerAs: Record<string, { color: TileColor | null; n: number }>; // 조커 해석(표시·점수용)
r: number; c: number; // 칸 판 위치: r줄 c칸부터 오른쪽으로 채운다(2026-10-14)
}
interface DraftSet { tileIds: string[]; as?: 'run' | 'group' }
interface Cell { id: string; r: number; c: number } // 작업 중인 바닥의 타일 하나(0 ≤ r < 12, 0 ≤ c < 20)
interface RummiState {
options: RummiOptions;
@@ -146,10 +153,7 @@ interface RummiState {
hasMelded: Record<PlayerId, boolean>; // 첫 등록 여부(공개)
current: PlayerId;
turnStartedAt: number;
draft: { // 현재 턴 초안
sets: DraftSet[];
history: DraftSet[][]; // 되돌리기 스택(최대 100)
} | null;
draft: { cells: Cell[]; edits: number }; // 현재 턴의 작업 중인 바닥(칸)과 놓은 횟수. 단계 기록 없음(§5.6)
consecutivePassesWithEmptyPool: number;
phase: 'playing' | 'finished';
endReason: 'rackEmpty' | 'stalemate' | null;
@@ -163,17 +167,18 @@ interface RummiState {
### 8.2 액션
| type | payload | 누가 / 언제 | 검증 조건 |
|---|---|---|---|
| `setDraft` | `{ sets: DraftSet[] }` | `current`, playing | 초안 보존 검사만 한다(아래 C1~C3). 세트 유효성은 보지 않는다. 초당 10회 제한(서버 레벨). 현재 초안을 history에 넣는다 |
| `undoDraft` | `{}` | `current` | history가 비어 있지 않음 |
| `resetDraft` | `{}` | `current` | 언제나 가능(초안을 턴 시작 테이블로) |
| `commit` | `{}` | `current` | 아래 "턴 확정 검증" 통과. 실패하면 `invalidCommitPenalty`에 따름 |
| `arrange` | `{ cells: Cell[], turn }` | `current`, playing | 놓을 때마다 작업 중인 바닥 전체. 보존 검사만 한다(아래 C1~C3). 묶음 유효성은 보지 않는다. 클라이언트는 놓을 때만 보낸다 |
| `drag` | `{ ids, x, y, turn }` | `current`, playing | **스트림 액션**(`isStreamAction`, 그림 맞히기 획과 같은 길): 끄는 중인 타일의 칸 단위 위치. 상태는 안 바뀌고 공개 이벤트만 모두에게 간다(뷰 재계산 없음, 기록은 묶어서 저장). 아직 바닥에 없는 받침대 타일은 `null`(뒷면)로 가린다. 클라이언트가 0.2초에 1번까지만 보낸다(소켓 한도 초당 20, `act()`의 대기 잠금을 거치지 않는 `socket.send`). 늦게 온 것·남의 것·옵션이 꺼진 방은 오류 없이 버린다. `ids: []` = 놓지 않고 끝남 |
| `resetDraft` | `{}` | `current` | 언제나 가능(바닥을 턴 시작 상태로, [되돌리기]) |
| `commit` | `{ cells?, turn }` | `current` | `cells`가 있으면 그 바닥을 보존 검사 후 한 번에 놓고 검증(컴퓨터, 마지막 손놓기와 겹칠 때). 아래 "턴 확정 검증" 통과. 실패하면 `invalidCommitPenalty`에 따름 |
| `draw` | `{}` | `current` | 초안이 턴 시작과 같거나, 다르면 초안을 버리고 뽑는다(UI에서 확인 대화상자). 풀이 비었으면 `pass`와 같다 |
| `pass` | `{}` | `current` | 풀이 비었을 때만 |
초안 보존 검사(`setDraft`)
- C1: 초안의 모든 타일 ID는 (턴 시작 테이블 타일 ∪ 내 랙 타일)에 속하고, 중복이 없다.
- C2: 턴 시작 테이블의 모든 타일이 초안에 들어 있다(테이블 → 랙 이동 금지).
- C3: 첫 등록 전(`hasMelded=false`)이고 `initialMeldAllowExtend=off`이면, 턴 시작 테이블의 세트들이 구성 그대로(같은 타일 집합) 초안에 있다.
바닥 보존 검사(`arrange`, `commit.cells`)
- C1: 모든 타일 ID는 (턴 시작 테이블 타일 ∪ 내 랙 타일)에 속하고, 중복이 없고, 칸 판 안에 있고, 한 칸에 하나다.
- C2: 턴 시작 테이블의 모든 타일이 바닥에 있다(테이블 → 랙 이동 금지, 조커도 마찬가지).
- C3: 첫 등록 전(`hasMelded=false`)이고 `initialMeldAllowExtend=off`이면, 턴 시작 테이블의 타일은 제자리 칸에서 움직일 수 없다. 그 옆에 랙 타일을 붙이는 것은 작업 중에는 되지만 [완료] 때 "첫 등록 전에는 바닥 묶음에 붙일 수 없어요"로 거부된다(묶음 구성이 턴 시작과 같아야 함).
- 턴 확정 검증의 묶음 = 칸 판에서 읽은 묶음(`stripsOf`). 확정되면 각 묶음은 그 자리(같은 줄·시작 칸)에 정규화된 순서(런은 오름차순)로 놓인다.
턴 확정 검증(`commit`, 시간 초과 판정 공용)
```ts
@@ -235,9 +240,10 @@ function normalizeSet(d: DraftSet, tiles): TableSet | null {
### 8.3 공개/비공개 정보 (view)
- 모두 공개(관전자 포함): 확정 테이블(`table`), 각 플레이어 랙 타일 수, 첫 등록 여부, 풀 남은 수, 현재 턴, 마감 시각, 매치 점수.
- 본인만: 자기 랙 타일 전체.
- 초안
- 현재 턴 플레이어는 자기 초안 전체와 각 세트의 유효 여부(실시간 검증 결과: 초록/빨강), 현재 첫 등록 점수 합계를 본다.
- 다른 사람과 관전자는 `showDraftToOthers = off`(기본)이면 "생각 중" 표시와 초안 변경 횟수만 받는다. `on`이면 초안 테이블 전체를 받는다. 이 경우 랙에서 꺼낸 타일이 보이는데, 실제 게임에서도 테이블에 올린 타일은 모두가 보므로 허용한다. 되돌려도 이미 본 정보는 남는다는 점을 옵션 설명에 적는다.
- 작업 중인 바닥(`draft: { cells, groups }`)
- 현재 턴 플레이어는 자기 바닥 전체와 각 묶음의 유효 여부(초록/빨강, 이유), 현재 첫 등록 점수 합계를 본다.
- 다른 사람과 관전자는 `showDraftToOthers = on`(기본, 앱처럼)이면 놓을 때마다 바닥 전체를 받고, 끄는 중인 타일은 `drag` 스트림 이벤트로 본다(받침대에서 아직 안 내려놓은 타일은 뒷면). 바닥에 올린 랙 타일이 보이는 것은 실제 게임과 같다. 되돌려도 이미 본 정보는 남는다는 점을 옵션 설명에 적는다. `off`면 "생각 중" 표시와 놓은 횟수만 받는다.
- `secretsOf`(누출 검사)는 바닥에 올린 타일을 그 사람의 숨은 타일에서 뺀다.
- 절대 보내지 않는 것: 풀 순서, 남의 랙, RNG 상태. 뽑기 이벤트는 본인에게만 타일 내용을 주고, 다른 사람에게는 "1개 뽑음"만 준다. 시간 초과 벌칙으로 되돌아간 타일 목록도 본인에게만 준다.
### 8.4 랜덤 요소 (시드 RNG 사용 지점)
@@ -251,7 +257,7 @@ function normalizeSet(d: DraftSet, tiles): TableSet | null {
- 초안 변경 없음 → 1개 뽑기 또는 넘기기.
- 유효 초안 → `commit` 또는 되돌리고 1개 뽑기.
- 무효 초안 → 되돌리고 `invalidTimeoutPenalty`개 뽑기(풀에 남은 만큼만).
- 연결이 끊겨도 초안은 서버에 남는다. 다시 들어오면 그대로 이어서 한다. 타이머는 멈추지 않는다.
- 연결이 끊겨도 작업 중인 바닥은 서버에 남는다. 다시 들어오면 그대로 이어서 한다. 타이머는 멈추지 않는다.
- 끊긴 플레이어가 계속 돌아오지 않으면(서버 정책: 연속 3턴 타임아웃) 이후 그 플레이어의 턴은 즉시 `draw`로 처리한다. 엔진은 `deadline`을 짧게 돌려주기만 하면 된다.
### 8.6 종료 조건과 결과(GameResult)
@@ -270,20 +276,22 @@ interface GameResult {
## 9. UI/UX
- 모바일 세로 화면
- 위: 상대 정보(이름, 남은 타일 수, 첫 등록 표시, 타이머 링).
- 가운데: 테이블. 세트를 줄 단위로 놓고 핀치 줌과 스크롤을 지원한다. 세트 사이에 "새 세트" 빈 칸이 있다.
- 아래: 내 랙 2줄. 타일 최소 44×60px이고 탭 영역은 48px 이상.
- 하단 고정 버튼: [정렬: 색별 | 숫자별] [되돌리기] [처음으로] [뽑기 / 완료]
- 가운데: 칸 판 테이블(§5.6). 화면 폭에 맞추되 좁은 화면은 칸을 키워(1.5~2배) 가로·세로로 스크롤한다. 머리줄의 [-]/[+]로 크기를 바꾼다(기기에 저장). 내 차례에는 칸 선이 보인다. 줄은 최소 6줄, 가장 아래 타일 밑으로 한 줄 더 보인다(최대 12줄).
- 아래: 내 랙. 타일 44×60px이고 탭 영역은 48px 이상.
- 하단 고정 버튼: [되돌리기] [도와줘 / 받침대로] [새 묶음] [한 장 가져오기 / 넘기기] [완료]. 정렬 [색깔순 | 숫자순]은 받침대 위.
- PC: 테이블이 넓고 랙은 아래 1~2줄이다.
- 조작
- 드래그 앤 드롭: 랙 ↔ 테이블, 테이블 세트 ↔ 세트, 세트 끝·중간에 끼우기, 세트 바깥에 놓으면 새 세트.
- 탭 두 번 방식: 타일을 탭해서 선택하고 놓을 곳을 탭한다. 드래그가 어려운 노년층을 위한 방식이고, 둘 다 지원한다.
- 여러 개 선택: 길게 눌러 여러 타일을 고르고 한꺼번에 옮긴다.
- 조작(2026-10-14, 앱 방식) — 마우스·터치 모두 포인터 이벤트
- 끌어다 놓기: 랙 → 바닥 아무 칸, 바닥 → 바닥(쪼개기·합치기·끼우기), 바닥에서 내가 이번 차례에 낸 타일 → 랙. 6px 넘게 움직이면 끌기, 그보다 짧으면 탭(고르기)이다. 고른 타일 중 하나를 끌면 고른 타일이 한 줄로 같이 움직인다. 놓을 곳은 노란 점선 칸으로 미리 보인다. 타일에는 `touch-action: none`을 줘서 휴대폰에서 끌 때 화면이 같이 밀리지 않게 하고, 빈 바닥을 밀면 스크롤된다.
- 탭 방식: 타일을 눌러 고르고 바닥의 빈 칸을 누르면 거기에 놓인다. [새 묶음]은 빈 곳에 따로 놓고, [받침대로]는 고른 타일 중 내가 낸 것을 받침대로 돌린다. 드래그가 어려운 노년층을 위한 방식이고, 둘 다 지원한다.
- 바닥 타일을 두 번 누르면 그 묶음을 통째로 고른다(앱의 "길게 눌러 묶음 끌기" 대신).
- 첫 등록 전에는 바닥 타일을 집을 수 없고, 바닥 묶음을 밀어내는 곳에도 놓을 수 없다(안내 문구).
- 다른 사람 화면: 차례인 사람이 놓을 때마다 타일이 칸 사이를 미끄러져 움직이고(CSS left/top 전환), 끄는 중인 타일은 반투명 그림자 줄로 0.2초마다 따라 움직인다. 손을 놓으면 그 타일이 그림자 자리에서 칸으로 들어간다. 미리 보기가 없던 타일(컴퓨터, 옵션 끔)은 그 사람 칸에서 날아온다.
- 자동 정렬
- "색별": 색(검정·빨강·파랑·주황) 다음 숫자 순.
- "숫자별": 숫자 다음 색 순. 조커는 맨 끝.
- 랙 배치 순서는 클라이언트 로컬 상태이고, 서버는 순서를 저장하지 않는다.
- 실시간 검증 표시: 초안의 각 세트에 초록 테두리(유효) 또는 빨강 테두리(무효)와 짧은 이유("같은 색이 두 개예요")를 보여 준다. 첫 등록 전에는 "첫 등록: 21 / 30점" 진행 막대를 보여 준다.
- "완료" 버튼은 초안이 유효할 때만 강조색으로 바뀐다(무효일 때도 누를 수는 있고, 누르면 이유를 보여 준다).
- 실시간 검증 표시: 새로 만들거나 바뀐 묶음에 초록 테두리(올바름), 틀린 묶음에 빨강 점선 테두리와 짧은 이유("같은 색이 두 개예요")를 묶음 위에 보여 준다. 그대로인 바닥 묶음은 테두리가 없다. 첫 등록 전에는 "첫 등록: 21 / 30점" 진행 막대를 보여 준다.
- "완료" 버튼은 바닥이 올바를 때만 강조색으로 바뀐다(틀렸을 때도 누를 수는 있고, 누르면 이유를 보여 주고 바닥이 흔들린다).
- 힌트(`hints`): "도와줘" 버튼을 누르면 랙에서 바로 낼 수 있는 새 세트 1개를 하이라이트한다. 재배치 탐색은 하지 않는다(계산량 제한). 클라이언트에서 자기 랙 정보만으로 계산하므로 서버 비공개 정보가 필요 없다.
- 애니메이션: 타일 이동 200ms, 세트 확정 때 반짝임, 다른 사람의 확정 때 바뀐 세트를 1초 동안 강조해서 무엇이 바뀌었는지 보이게 한다.
- 색 구분: 숫자 아래에 색별 모양(검정 ●, 빨강 ♥, 파랑 ◆, 주황 ★)을 넣어 색약 사용자도 구별할 수 있게 한다.
@@ -291,9 +299,9 @@ interface GameResult {
### 9.1 소리·움직임
소리는 모두 화면 안에서 합성한다(플라스틱 타일 "딱" 소리 = 짧은 잡음 + 높은 음). 상대·컴퓨터의 행동은 화면 정보가 바뀔 때 울리고, 처음 들어왔을 때·다시 접속했을 때는 울리지 않는다. 내 타일 옮기기처럼 서버에 보이지 않는 조작만 누르는 순간 울린다.
- 타일 고르기: 가벼운 "틱". 바닥·받침대에 놓기: "딱". 되돌리기·처음으로: 휙.
- 타일 옮기기(내 화면): 고른 타일이 원래 자리(받침대·다른 묶음)에서 놓은 자리로 미끄러져 간다(`flyFrom`).
- 확정(누구든): 놓은 장수만큼 "딱딱딱"(최대 5번). 내 확정이면 성공음이 더해진다. 다른 사람이 바닥에 새로 놓은 타일(보이는 초안 포함)은 그 사람 칸에서 날아오고, 바뀐 묶음은 노랗게 반짝인다.
- 타일 고르기·집기: 가벼운 "틱". 바닥·받침대에 놓기: "딱". 되돌리기: 휙.
- 타일 옮기기(내 화면): 끌던 타일은 손을 놓은 자리에서, 눌러 옮긴 타일은 원래 자리(받침대·다른 칸)에서 칸으로 미끄러져 들어간다(`flyFrom`). 바닥 안에서 밀린 타일은 칸 사이를 미끄러진다.
- 확정(누구든): 놓은 장수만큼 "딱딱딱"(최대 5번). 내 확정이면 성공음이 더해진다. 다른 사람이 바닥에 새로 놓은 타일은 끌던 그림자 자리(미리 보기가 없으면 그 사람 칸)에서 날아오고, 바뀐 묶음은 노랗게 반짝인다.
- 첫 등록: 성공음 + 배너("첫 등록!", 아래에 누가 했는지).
- 틀린 확정(서버가 받아 주지 않을 때): 실패음 + 바닥이 흔들린다(anim-shake).
- 한 장 가져오기(누구든): 미끄러지는 소리 뒤에 "딱". 내가 가져온 타일은 "남은 타일"에서 받침대로 날아오고, 다른 사람이 가져가면 뒤집힌 타일이 그 사람 칸으로 날아간다(`flyGhost`).
@@ -308,22 +316,26 @@ interface GameResult {
- [ ] 세트 판정: [빨강12, 빨강13, 빨강1]은 무효. [파랑5, 빨강5, 파랑5]는 무효(색 중복). 5개짜리 그룹은 무효. [빨강1, 빨강2]는 무효(2개).
- [ ] 조커 해석: [조커, 검정9, 검정10]을 이 순서로 보내면 8-9-10(27점)이라 첫 등록이 거부된다. [검정9, 검정10, 조커]로 보내면 9-10-11(30점)이라 허용된다.
- [ ] [빨강12, 빨강13, 조커]는 위쪽으로 붙일 수 없으므로 11-12-13으로 해석된다(유효).
- [ ] 첫 등록 전 플레이어가 테이블 세트에 랙 타일을 붙이면 거부된다. 테이블 세트를 쪼개는 초안은 `setDraft`(C3)에서 거부된다.
- [ ] 첫 등록 전 플레이어가 테이블 세트 옆에 랙 타일을 붙이면 완료가 거부된다. 테이블 타일을 옮기는(쪼개는) `arrange`는 C3에서 거부된다.
- [ ] 재배치: 테이블 [빨강4..8] + 랙 빨강6 → [빨강4,5,6] [빨강6,7,8] 확정이 성공한다.
- [ ] 조커 회수: 테이블 [파랑5, 조커, 파랑7] + 랙 [파랑6, 검정3, 빨강3] → [파랑5,6,7] [검정3, 빨강3, 조커] 성공. 조커가 테이블에서 사라지는(랙으로 가는) 초안은 C2로 거부된다.
- [ ] 조커 회수: 테이블 [파랑5, 조커, 파랑7] + 랙 [파랑6, 검정3, 빨강3] → [파랑5,6,7] [검정3, 빨강3, 조커] 성공. 조커가 테이블에서 사라지는(랙으로 가는) 바닥은 C2로 거부된다. 첫 등록 전에는 조커를 옮길 수 없다.
- [ ] 랙 타일 없이 재배치만 하고 `commit`하면 "랙에서 타일을 1개 이상 내야 해요"로 거부된다.
- [ ] 시간 초과: 무효 초안 상태에서 마감이 지나면 테이블이 턴 시작 상태로 복구되고 랙도 원래대로 돌아온 뒤 3개를 뽑는다. 풀에 2개만 있으면 2개만 뽑는다.
- [ ] 시간 초과: 유효 초안이면(`commit` 옵션) 자동 확정된다. 변경이 없으면 1개를 뽑는다.
- [ ] 되돌리기: `setDraft` 5회 후 `undoDraft` 2회 → 3번째 초안 상태. `resetDraft` → 턴 시작 상태. 재접속해도 초안이 유지된다.
- [ ] 시간 초과(앱 기본): 올바른 바닥도, 틀린 바닥도 턴 시작 상태로 복구되고 랙도 원래대로 돌아온 뒤 1개를 뽑는다. 자리만 옮긴 것은 벌칙 없이 1개.
- [ ] 시간 초과(규칙서 옵션): 틀린 바닥이면 3개, 풀에 2개만 있으면 2개만 뽑는다. `commit` 옵션이면 올바른 바닥은 자동 완료된다.
- [ ] 되돌리기: `arrange` 여러 번 뒤 `resetDraft` → 턴 시작 상태. 재접속해도 작업 중인 바닥이 유지된다.
- [ ] 칸 판: 나란히 붙은 타일이 한 묶음, 빈칸으로 나뉨. 타일 위에 놓으면 오른쪽이 밀림, 줄 끝을 넘으면 거부. 한 칸에 두 장·판 밖·남의 타일은 거부. 확정된 묶음끼리는 칸 판에서 붙지 않는다(무작위 대국 불변식).
- [ ] 모두에게 보이기: 기본 옵션에서 상대·관전자 view에 바닥에 올린 타일만 있고 랙의 나머지는 없다. `drag` 이벤트는 바닥에 없는 랙 타일을 `null`로 가리고 상태를 바꾸지 않는다.
- [ ] 예전 저장(v1)을 `migrate`하면 칸 위치가 붙고 이어서 둘 수 있다.
- [ ] 점수: 4인 예시(B -15, C 조커 -30, D -15, A +60). 교착 종료 예시(A +32, B -7, C -25).
- [ ] 교착 종료: 풀이 빈 3인 게임에서 3명이 연속 넘기면 종료된다. 중간에 누가 `commit`하면 카운트가 0으로 초기화된다.
- [ ] 정보 유출: 관전자와 상대 view에 남의 랙 타일 ID·숫자, 풀 내용이 없다. `showDraftToOthers=off`이면 초안 타일도 없다. 뽑기 이벤트에 타일 내용이 본인에게만 있다.
- [ ] 동시성: 같은 `commit` 패킷이 두 번 오면 두 번째는 "차례가 아니에요"로 거부된다. 턴이 넘어간 뒤 도착한 이전 턴 `setDraft`도 거부된다.
- [ ] 동시성: 같은 `commit` 패킷이 두 번 오면 두 번째는 "차례가 아니에요"로 거부된다. 턴이 넘어간 뒤 도착한 이전 턴 `arrange`도 거부된다.
## 11. 참고 자료
- Rummikub 공식 영문 규칙서(2600-English): https://rummikub.com/wp-content/uploads/2019/12/2600-English-1.pdf (106타일, 14개 분배, 첫 등록 30점, 조커 회수, 1분 제한, 미완성 시 3개 벌칙, 풀 소진 처리, 점수 계산, 조커 30점)
- Wikipedia "Rummikub": https://en.wikipedia.org/wiki/Rummikub
- 나무위키 "루미큐브": https://namu.wiki/w/루미큐브 (조커 감점 30점 공식 / 50점 대회 룰, 2~4명)
- 루미큐브 앱 (§13): App Store 설명 https://apps.apple.com/us/app/rummikub/id1015322991 (턴 시간·상대 수 설정, 연습 게임), App Store 리뷰 https://apps.apple.com/us/app/rummikub/id973113361?see-all=reviews&platform=iphone (Undo = 차례 전체 되돌리기, 시간 초과 = 차례 전체 되돌리고 1장, 묶음 끌기), 앱 사용자 정리 https://game-solver.com/rummikub-2/ (턴 시간 무제한(컴퓨터 상대)·15초·30초·1분·2분, 단계 되돌리기 없음)
## 12. 메모 (상표·법적 주의 등)
- **표시 이름(2026-10-06 확정)**: 친구끼리 쓰는 사이트라 원래 이름 "루미큐브"으로 표시한다(`13-decisions.md` 0절). 아래 상표 메모는 공개 서비스로 바꿀 때를 위한 참고로 남긴다.
@@ -333,3 +345,26 @@ interface GameResult {
- 승리 시 "루미큐브!" 외침 대신 "다 냈다!" 같은 일반 문구를 쓴다.
- 타일 디자인(둥근 숫자, 웃는 얼굴 조커 등 원작 고유 그래픽)을 따라 하지 않는다. 게임 규칙 자체는 저작권 보호 대상이 아니지만 규칙서 문장과 그림은 보호 대상이므로 직접 작성한다.
- 돈, 칩을 쓰지 않는다. 점수는 방 안 결과 표시용이다.
## 13. 루미큐브 앱 규칙 조사 (2026-10-14)
사용자 요청: "루미큐브 규칙 루미큐브 앱 규칙으로 변경", "드래그해서 화면에 놔두고 합치는 방식(루미큐브 앱처럼)으로 변경 — 모두한테 보이게 설정". 앱 안의 규칙 화면은 공개 문서가 없어서 공식 규칙서·앱 스토어 설명·앱 리뷰·사용자 정리를 같이 봤다.
| 항목 | 종이 규칙서(2600-English) | 앱 | 이 사이트(기본) |
|---|---|---|---|
| 타일·분배 | 106장(조커 2), 14장 | 같음 | 같음(그대로) |
| 첫 등록 | 랙 타일만으로 30점 이상, 조커는 대신하는 숫자 | 같음 | 같음(그대로) |
| 바닥 조작 | 묶음 쪼개기·합치기 | 칸 판에 끌어다 놓기, 나란히 붙으면 한 묶음 | **칸 판 끌어다 놓기**(§5.6) |
| 되돌리기 | — | 차례 전체만 되돌림("no incremental undos") | **[되돌리기] = 차례 처음으로**(예전 한 단계 되돌리기·처음으로 두 버튼을 하나로) |
| 턴 시간 | 1분 | 15초·30초·1분·2분(컴퓨터 상대 무제한) | 1분 기본, **30초 추가**, 90·120·180초·무제한 유지 |
| 시간 초과(아무것도 안 함) | 1장 | 1장 | 1장(그대로) |
| 시간 초과(올바르게 놓아 둠) | 완료 전이면 미완성 | 차례 전체 되돌리고 1장("your entire turn is reset and you are penalized another tile") | **되돌리고 1장**(예전 기본 "자동 확정"은 옵션) |
| 시간 초과(틀린 바닥) | 되돌리고 3장 | 되돌리고 1장(같은 리뷰) | **1장**(예전 기본 3장은 옵션) |
| 틀린 채로 완료 | — | 완료가 안 됨 | 알려 주고 계속 고치기(그대로) |
| 조커 회수 | 첫 등록 뒤, 같은 차례에 다시 써야 함 | 같음(조커도 끌어 옮김) | 같음(그대로). 바닥 타일은 받침대로 못 가져오므로 자동으로 지켜짐 |
| 풀이 비었을 때 | 아무도 못 낼 때까지 | 같음 | 같음(그대로) |
| 점수 | 남은 타일 합, 조커 30 | 같음 | 같음(그대로) |
| 판 수 | 인원수만큼(1라운드) | 한 판씩(토너먼트 별도) | 1판(그대로) |
| 상대의 조작 보기 | 테이블에서 다 보임 | 상대가 옮기는 타일이 보임 | **기본 켬**(예전 기본 끔) + 끄는 중인 타일 미리 보기 |
- 확실하지 않은 점: 앱의 "틀린 바닥 시간 초과" 장수는 리뷰 문장("penalized another tile")으로만 확인했다(공식 앱 도움말 비공개). 그래서 종이 규칙서의 3장을 옵션으로 남겼다. 앱 칸 판의 정확한 크기는 확인하지 못해 20 × 12로 정했다(13장 런 + 106장이 다 들어가는 크기).
- 옵션은 새로 만들지 않고 기존 옵션의 기본값만 바꿨다(`timeoutValidDraft` commit→revert, `invalidTimeoutPenalty` 3→1, `showDraftToOthers` off→on). `turnSeconds`에 30을 더했다.

View File

@@ -58,9 +58,13 @@ async function finishHand(pages: Page[]) {
for (const p of pages) await p.getByText('이번 판 결과').first().waitFor({ timeout: 10_000 });
}
/** 루미큐브: whoever has the turn tries "도와줘" → "새 묶음" → "확정"; otherwise takes one tile. */
/**
* 루미큐브: whoever has the turn tries "도와줘" → places the picked tiles → "완료"; otherwise takes one tile.
* The first play drags the picked tiles from the rack onto the grid with the mouse, checks that the other player
* sees them on the table before 완료 (live working table), resets with "되돌리기", then places them with "새 묶음".
*/
async function rummikubTurns(pages: Page[], turns: number) {
const stats = { plays: 0, draws: 0, undo: false };
const stats = { plays: 0, draws: 0, dragged: false };
const myTurn = (p: Page) => p.evaluate(() => !!document.querySelector('.turn-status')?.textContent?.includes('내 차례예요'));
const bar = (p: Page) => p.getByRole('group', { name: '내 차례 행동' });
/** Waits until a bar button is enabled / disabled (server answered). */
@@ -77,6 +81,7 @@ async function rummikubTurns(pages: Page[], turns: number) {
if (!mover) await pages[0]!.waitForTimeout(100);
}
if (!mover) throw new Error(`nobody has the turn (turn ${n + 1})`);
const others = pages.filter((p) => p !== mover);
await bar(mover).waitFor();
let played = false;
await bar(mover).getByRole('button', { name: '도와줘' }).click();
@@ -84,23 +89,52 @@ async function rummikubTurns(pages: Page[], turns: number) {
if (picked > 0) {
// Tap one picked tile twice (deselect, select again) — the tap-to-select path.
const first = mover.locator('.rk-rack button[aria-pressed="true"]').first();
const label = await first.getAttribute('aria-label');
const id = (await first.getAttribute('data-tile'))!;
await first.click();
await mover.locator(`.rk-rack button[aria-label="${label}"]`).first().click();
await bar(mover).getByRole('button', { name: '새 묶음' }).click();
await mover.locator('.rk-set').last().waitFor();
if (!stats.undo) {
// Undo once (back to the turn start), then place again.
await mover.waitForTimeout(450); // not a double tap
await mover.locator(`.rk-rack [data-tile="${id}"]`).click();
if (!stats.dragged) {
// Drag the picked tiles onto the grid (mouse), row 2, column 2.
const tile = await mover.locator(`.rk-rack [data-tile="${id}"]`).boundingBox();
const board = await mover.locator('.rk-board').boundingBox();
if (!tile || !board) throw new Error('no tile / board box');
await mover.mouse.move(tile.x + tile.width / 2, tile.y + tile.height / 2);
await mover.mouse.down();
const cw = board.width / 20;
const tx = board.x + cw * 2.5;
const ty = board.y + cw * 1.36 * 2.5;
for (let k = 1; k <= 12; k++) await mover.mouse.move(tile.x + ((tx - tile.x) * k) / 12, tile.y + ((ty - tile.y) * k) / 12);
// While the tiles are still in hand, the others see them moving (drag preview stream, face down from the rack).
for (const o of others) await o.locator('.rk-ghostrow .rk-back').first().waitFor({ timeout: 5000 });
// The last position reaches them too (trailing preview), so the ghost row ends up over the board.
for (const o of others)
await o.waitForFunction(
() => {
const g = document.querySelector('.rk-ghostrow .rk-back')?.getBoundingClientRect();
const b = document.querySelector('.rk-board')?.getBoundingClientRect();
return !!g && !!b && g.top < b.top + b.height / 2;
},
null,
{ timeout: 5000 },
);
await mover.screenshot({ path: join(SHOTS, 'rummikub-3-dragging.png') });
await others[0]!.screenshot({ path: join(SHOTS, 'rummikub-4-dragging-seen-by-other.png') });
await mover.mouse.up();
await mover.locator(`.rk-board [data-tile="${id}"]`).waitFor({ timeout: 5000 });
// Everybody else sees the tile on the table right away (before 완료).
for (const o of others) await o.locator(`.rk-board [data-tile="${id}"]`).waitFor({ timeout: 5000 });
await barButton(mover, '되돌리기', true);
await bar(mover).getByRole('button', { name: '되돌리기' }).click();
await barButton(mover, '처음으로', false);
stats.undo = true;
await mover.locator(`.rk-rack [data-tile="${id}"]`).waitFor({ timeout: 5000 });
for (const o of others) await o.locator(`.rk-board [data-tile="${id}"]`).waitFor({ state: 'detached', timeout: 5000 });
stats.dragged = true;
await bar(mover).getByRole('button', { name: '도와줘' }).click();
await bar(mover).getByRole('button', { name: '새 묶음' }).click();
}
const commit = bar(mover).getByRole('button', { name: '확정' });
await bar(mover).getByRole('button', { name: '새 묶음' }).click();
await mover.locator(`.rk-board [data-tile="${id}"]`).waitFor({ timeout: 5000 });
const commit = bar(mover).getByRole('button', { name: '완료' });
await mover
.waitForFunction(() => [...document.querySelectorAll('.rk-bar button')].some((b) => b.textContent === '확정' && b.classList.contains('btn-primary') && !b.hasAttribute('disabled')), null, { timeout: 5000 })
.waitForFunction(() => [...document.querySelectorAll('.rk-bar button')].some((b) => b.textContent === '완료' && b.classList.contains('btn-primary') && !b.hasAttribute('disabled')), null, { timeout: 5000 })
.then(
() => (played = true),
() => {},
@@ -109,7 +143,7 @@ async function rummikubTurns(pages: Page[], turns: number) {
await commit.click();
stats.plays++;
} else {
await bar(mover).getByRole('button', { name: '처음으로' }).click();
await bar(mover).getByRole('button', { name: '되돌리기' }).click();
await mover.waitForTimeout(300);
}
}
@@ -121,7 +155,7 @@ async function rummikubTurns(pages: Page[], turns: number) {
}
await mover.waitForFunction(() => !document.querySelector('.turn-status')?.textContent?.includes('내 차례예요'), null, { timeout: 5000 });
}
console.log(` rummikub: ${stats.plays} plays, ${stats.draws} draws, undo ${stats.undo ? 'used' : 'not used'}`);
console.log(` rummikub: ${stats.plays} plays, ${stats.draws} draws, drag ${stats.dragged ? 'used' : 'not used'}`);
return stats;
}

View File

@@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test';
import { SeededRng, seedN, type PlayerId } from '@bg/engine';
import { decideBotAction } from '../bots/index';
import { botPlayout } from '../bots/playout';
import { ALL_TILE_IDS, normalizeSet, rummikub, type RummikubAction, type RummikubOptions, type RummikubState } from './index';
import { ALL_TILE_IDS, cellsOf, layoutSets, normalizeSet, rummikub, stripsOf, type RummikubAction, type RummikubOptions, type RummikubState } from './index';
const ME = 'bot:1:x';
const OTHER = 'human0';
@@ -14,18 +14,19 @@ function rig(o: { rack: string[]; table?: string[][]; melded?: boolean; opts?: P
const otherRack = ALL_TILE_IDS.filter((id) => !o.rack.includes(id) && !table.flat().includes(id)).slice(-14);
const used = new Set([...o.rack, ...table.flat(), ...otherRack]);
s.racks = { [ME]: [...o.rack], [OTHER]: otherRack };
const strips = layoutSets(table)!;
s.table = table.map((ids, i) => {
const n = normalizeSet({ tileIds: ids })!;
return { id: `s${i + 1}`, tileIds: n.tileIds, kind: n.kind, jokerAs: n.jokerAs };
return { id: `s${i + 1}`, tileIds: n.tileIds, kind: n.kind, jokerAs: n.jokerAs, r: strips[i]!.r, c: strips[i]!.c };
});
s.pool = ALL_TILE_IDS.filter((id) => !used.has(id));
s.current = ME;
s.hasMelded = { [ME]: !!o.melded, [OTHER]: true };
s.draft = { sets: s.table.map((t) => ({ tileIds: [...t.tileIds], as: t.kind })), history: [], edits: 0 };
s.draft = { cells: cellsOf(s.table), edits: 0 };
return s;
}
/** Lets the bot finish its turn (draft, then commit); returns the actions it took. */
/** Lets the bot finish its turn; returns the actions it took. */
function botTurn(s: RummikubState): { state: RummikubState; acts: RummikubAction[] } {
const acts: RummikubAction[] = [];
let now = 1000;
@@ -41,7 +42,7 @@ describe('rummikub bot', () => {
test('makes the 30-point first meld from its rack and commits it in the same turn', () => {
const s = rig({ rack: ['R10a', 'R11a', 'R12a', 'K3a', 'B3a', 'O3a', 'B7a', 'K9b'] });
const { state, acts } = botTurn(s);
expect(acts.map((a) => a.type)).toEqual(['setDraft', 'commit']);
expect(acts.map((a) => a.type)).toEqual(['commit']);
expect(state.hasMelded[ME]).toBe(true);
expect(state.racks[ME]!.sort()).toEqual(['B7a', 'K9b']);
});
@@ -57,14 +58,17 @@ describe('rummikub bot', () => {
test('after melding it lays tiles off on table sets (extending runs repeatedly)', () => {
const s = rig({ rack: ['B8a', 'B9a', 'O5a', 'K1a'], table: [['B5a', 'B6a', 'B7a'], ['R5a', 'K5a', 'B5b']], melded: true });
const { state, acts } = botTurn(s);
expect(acts.map((a) => a.type)).toEqual(['setDraft', 'commit']);
expect(acts.map((a) => a.type)).toEqual(['commit']);
expect(state.racks[ME]).toEqual(['K1a']);
expect(state.table.map((t) => t.tileIds.length).sort()).toEqual([4, 5]);
// The run stays where it was and grows to the right; the group it grew into moves to a free place.
expect(state.table.find((t) => t.tileIds.includes('B5a'))).toMatchObject({ r: 0, c: 0 });
expect(stripsOf(cellsOf(state.table))).toHaveLength(2);
});
test('a half-built draft (left from a timeout race) is dropped by drawing, never committed', () => {
test('a half-built working table (left from a timeout race) is dropped by drawing, never committed', () => {
let s = rig({ rack: ['R1a', 'B9a', 'K4a'], melded: true });
s = rummikub.apply(s, ME, { type: 'setDraft', sets: [{ tileIds: ['R1a'] }] }, { rng: SeededRng.fromSeed(seedN(2)), now: 500 }).state;
s = rummikub.apply(s, ME, { type: 'arrange', cells: [{ id: 'R1a', r: 3, c: 3 }] }, { rng: SeededRng.fromSeed(seedN(2)), now: 500 }).state;
const { state, acts } = botTurn(s);
expect(acts.map((a) => a.type)).toEqual(['draw']);
expect(state.racks[ME]).toHaveLength(4);

View File

@@ -1,12 +1,11 @@
/**
* 루미큐브 computer player. A turn is two decisions: first one `setDraft` with the whole plan (rack-only sets, then
* single tiles laid off on table / new sets), then `commit` once the view says the draft is valid. If the draft is
* not valid (should not happen) it draws, which also throws the draft away — it never leaves a half-built draft.
* Table sets are never rearranged beyond adding tiles to their ends.
* 루미큐브 computer player. A turn is one decision: the whole plan (rack-only sets, then single tiles laid off on
* table / new sets) laid out on the grid and sent as `commit` with its cells, or a draw. Table sets are never
* rearranged beyond adding tiles to their ends; they keep their places when there is room.
*/
import type { BotStrategy } from '../bots/types';
import { answerRequests } from '../bots/policy';
import { extendSet, isJoker, pickDisjoint, type JokerAs } from './rules';
import { cellsOf, extendSet, isJoker, layoutSets, pickDisjoint, type JokerAs } from './rules';
import type { RummikubAction, RummikubView } from './index';
type Plan = { tileIds: string[]; kind: 'run' | 'group'; jokerAs: Record<string, JokerAs> };
@@ -35,9 +34,8 @@ export const rummikubBot: BotStrategy<RummikubView, RummikubAction> = ({ view, l
if (req) return req;
if (legal.some((a) => a.type === 'ready')) return { type: 'ready' };
const my = view.my!;
// Drawing also throws away anything left on the working table (e.g. after a timeout race).
const endTurn: RummikubAction = legal.find((a) => a.type === 'pass') ?? { type: 'draw' };
// Second step of a turn: the plan is on the table — commit it, or give up cleanly (draw resets the draft).
if (my.changed) return my.check?.ok ? { type: 'commit', turn: view.turnNo } : endTurn;
const rack = my.rack;
const table: Plan[] = view.table.map((t) => ({ tileIds: [...t.tileIds], kind: t.kind, jokerAs: t.jokerAs }));
@@ -58,5 +56,10 @@ export const rummikubBot: BotStrategy<RummikubView, RummikubAction> = ({ view, l
}
const before = new Set(view.table.flatMap((t) => t.tileIds));
if (!sets.some((s) => s.tileIds.some((id) => !before.has(id)))) return endTurn;
return { type: 'setDraft', sets: sets.map((s) => ({ tileIds: s.tileIds, as: s.kind })), turn: view.turnNo };
const strips = layoutSets(
sets.map((s) => s.tileIds),
view.table,
);
if (!strips) return endTurn;
return { type: 'commit', cells: cellsOf(strips), turn: view.turnNo };
};

View File

@@ -3,18 +3,28 @@ import { z } from 'zod';
import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng, type Validation } from '@bg/engine';
import {
ALL_TILE_IDS,
BOARD_COLS,
BOARD_ROWS,
arrangementKey,
cellKey,
cellsKey,
cellsOf,
extendSet,
findMeld,
isJoker,
freeSpot,
inBoard,
layoutSets,
pickDisjoint,
normalizeSet,
rackValue,
setProblem,
stripsOf,
tileOf,
type Cell,
type DraftSet,
type JokerAs,
type NormalSet,
type Strip,
type TileColor,
} from './rules';
@@ -23,47 +33,61 @@ export * from './rules';
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>[]]);
/** Defaults follow the Rummikub app (§2, docs/13-decisions.md); the printed rulebook's choices stay selectable. */
export const rummikubOptionsSchema = z.object({
initialMeldPoints: lit(0, 20, 30, 50)
.default(30)
.meta({ title: '첫 등록 최소 점수', labels: { 0: '없음', 20: '20점', 30: '30점(공식)', 50: '50점' } }),
turnSeconds: lit(60, 90, 120, 180, null)
turnSeconds: lit(30, 60, 90, 120, 180, null)
.default(60)
.meta({ title: '한 차례 제한 시간', labels: { 60: '1분(공식)', 90: '1분 30초', 120: '2분', 180: '3분', null: '무제한' } }),
.meta({ title: '한 차례 제한 시간', labels: { 30: '30초', 60: '1분(공식)', 90: '1분 30초', 120: '2분', 180: '3분', null: '무제한' } }),
timeoutValidDraft: z
.enum(['commit', 'revert'])
.default('commit')
.meta({ title: '시간이 다 됐을 때 올바르게 놓아 둔 타일', labels: { commit: '자동으로 확정', revert: '되돌리고 한 장 가져오기(공식)' } }),
.default('revert')
.meta({ title: '시간이 다 됐을 때 올바르게 놓아 둔 타일', labels: { commit: '자동으로 완료', revert: '되돌리고 한 장 가져오기(앱·공식)' } }),
invalidTimeoutPenalty: lit(1, 3)
.default(3)
.meta({ title: '시간이 다 됐는데 덜 맞췄을 때 가져올 장수', labels: { 1: '1장', 3: '3장(공식)' } }),
.default(1)
.meta({ title: '시간이 다 됐는데 덜 맞췄을 때 가져올 장수', labels: { 1: '1장(앱)', 3: '3장(종이 규칙서)' } }),
invalidCommitPenalty: z
.enum(['reject', 'penalty3'])
.default('reject')
.meta({ title: '틀린 채로 확정을 누르면', labels: { reject: '알려 주고 계속 고치기', penalty3: '되돌리고 3장 가져오기' } }),
.meta({ title: '틀린 채로 완료를 누르면', labels: { reject: '알려 주고 계속 고치기(앱)', penalty3: '되돌리고 3장 가져오기' } }),
jokerPenalty: lit(30, 50)
.default(30)
.meta({ title: '받침대에 남은 조커 감점', labels: { 30: '30점(공식)', 50: '50점(대회)' } }),
initialMeldAllowExtend: z.boolean().default(false).meta({ title: '첫 등록하는 차례에 바닥 묶음에도 붙이기 허용' }),
showDraftToOthers: z.boolean().default(false).meta({ title: '고민 중인 배치를 다른 사람에게 보이기(되돌려도 이미 본 타일은 남아요)' }),
showDraftToOthers: z.boolean().default(true).meta({ title: '옮기는 타일을 모두에게 바로 보이기(앱처럼, 되돌려도 이미 본 타일은 남아요)' }),
gamesPerMatch: z
.enum(['1', 'players', '2', '3', '4'])
.default('1')
.meta({ title: '판 수', labels: { 1: '1판', players: '인원수만큼(공식)', 2: '2판', 3: '3판', 4: '4판' } }),
.meta({ title: '판 수', labels: { 1: '1판(앱)', players: '인원수만큼(종이 규칙서)', 2: '2판', 3: '3판', 4: '4판' } }),
hints: z.boolean().default(true).meta({ title: '"도와줘" 힌트 버튼' }),
});
export type RummikubOptions = z.infer<typeof rummikubOptionsSchema>;
const draftSetSchema = z.object({
tileIds: z.array(z.string().max(4)).min(1).max(106),
as: z.enum(['run', 'group']).optional(),
const cellSchema = z.object({
id: z.string().max(4),
r: z.number().int().min(0).max(BOARD_ROWS - 1),
c: z.number().int().min(0).max(BOARD_COLS - 1),
});
export const rummikubActionSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('setDraft'), sets: z.array(draftSetSchema).max(106), turn: z.number().int().optional() }),
z.object({ type: z.literal('undoDraft') }),
/** The whole working table after one drop (§5.6): checked loosely, shown to everybody. */
z.object({ type: z.literal('arrange'), cells: z.array(cellSchema).max(106), turn: z.number().int().optional() }),
/**
* Live drag preview (stream action, a few per second): the tiles in hand are at grid position (x, y), in cells.
* `ids` empty = the drag ended without a drop.
*/
z.object({
type: z.literal('drag'),
ids: z.array(z.string().max(4)).max(BOARD_COLS),
x: z.number().min(-4).max(BOARD_COLS + 4),
y: z.number().min(-4).max(BOARD_ROWS + 6),
turn: z.number().int().optional(),
}),
z.object({ type: z.literal('resetDraft') }),
z.object({ type: z.literal('commit'), turn: z.number().int().optional() }),
/** Ends the turn. `cells` (optional) is the final table, put down and checked in one step (computers, last drop). */
z.object({ type: z.literal('commit'), cells: z.array(cellSchema).max(106).optional(), turn: z.number().int().optional() }),
z.object({ type: z.literal('draw') }),
z.object({ type: z.literal('pass') }),
z.object({ type: z.literal('ready') }),
@@ -79,6 +103,9 @@ export interface TableSet {
tileIds: string[];
kind: 'run' | 'group';
jokerAs: Record<string, JokerAs>;
/** Grid position of the first tile; the set fills row `r` to the right. */
r: number;
c: number;
}
export type MoveKind = 'commit' | 'draw' | 'pass' | 'timeoutCommit' | 'timeoutDraw' | 'penalty' | 'left';
@@ -126,7 +153,8 @@ export interface RummikubState {
current: PlayerId;
turnNo: number;
turnStartedAt: number;
draft: { sets: DraftSet[]; history: DraftSet[][]; edits: number };
/** The current player's working table (grid cells) and how many drops they made this turn. */
draft: { cells: Cell[]; edits: number };
timeoutsInRow: Record<PlayerId, number>;
consecutivePasses: number;
/** Tiles each player drew at the end of their last turn (shown only to them). */
@@ -145,17 +173,17 @@ export interface RummikubState {
// ---------------------------------------------------------------- view
export interface DraftSetView {
/** One set on the working table with its live check (green / red outline on screen). */
export interface GroupView {
tileIds: string[];
as?: 'run' | 'group';
r: number;
c: number;
ok: boolean;
/** Short reason when not valid. */
problem: string | null;
kind: 'run' | 'group' | null;
jokerAs: Record<string, JokerAs>;
points: number;
/** Both readings possible ([빨강5, 조커, 조커]) — the screen offers a toggle. */
ambiguous: boolean;
}
export interface SeatView {
@@ -172,12 +200,23 @@ export interface SeatView {
export interface TurnCheck {
ok: boolean;
reason: string | null;
/** Indexes into `draft.groups` of the sets that are not valid. */
invalidIdx: number[];
/** Points of new rack-only sets (first meld progress). */
meldPoints: number;
fromRack: number;
}
/** Drag preview event (stream): tiles that are not on the table yet are hidden (null). */
export interface DragEvent {
type: 'drag';
player: PlayerId;
turn: number;
tiles: (string | null)[];
x: number;
y: number;
}
export interface RummikubView {
phase: RummikubState['phase'];
options: RummikubOptions;
@@ -188,19 +227,20 @@ export interface RummikubView {
/** 0 = 무제한. */
turnMs: number;
poolCount: number;
/** The committed table (positions included). */
table: TableSet[];
lastChanged: string[];
log: LogEntry[];
/** Number of edits the current player made this turn (shown as "생각 중"). */
/** Number of drops the current player made this turn (shown as "생각 중"). */
draftEdits: number;
/** Full draft: the current player always, others only with showDraftToOthers. */
draft: DraftSetView[] | null;
/** Working table: the current player always, everybody else with showDraftToOthers (live, §5.6). */
draft: { cells: Cell[]; groups: GroupView[] } | null;
me: PlayerId | null;
my: {
rack: string[];
lastDrawn: string[];
melded: boolean;
canUndo: boolean;
/** Anything moved this turn (되돌리기 is useful). */
changed: boolean;
check: TurnCheck | null;
needReady: boolean;
@@ -223,66 +263,87 @@ function turnLimitMs(s: RummikubState): number | null {
return s.options.turnSeconds === null ? null : s.options.turnSeconds * 1000;
}
const ROUND_END_MS = 30_000;
const HISTORY_MAX = 100;
const activeSeats = (s: RummikubState): PlayerId[] => s.roundPlayers.filter((p) => !s.left.includes(p));
const startSets = (s: RummikubState): DraftSet[] => s.table.map((t) => ({ tileIds: [...t.tileIds], as: t.kind }));
const startCells = (s: RummikubState): Cell[] => cellsOf(s.table);
const tableTiles = (s: RummikubState): Set<string> => new Set(s.table.flatMap((t) => t.tileIds));
const draftChanged = (s: RummikubState): boolean => arrangementKey(s.draft.sets) !== arrangementKey(s.table);
const cleanSet = (d: DraftSet): DraftSet => (d.as ? { tileIds: [...d.tileIds], as: d.as } : { tileIds: [...d.tileIds] });
const setsOfCells = (cells: readonly Cell[]): DraftSet[] => stripsOf(cells).map((x) => ({ tileIds: x.tileIds }));
/** The sets differ from the turn start (moving whole sets around does not count). */
const draftChanged = (s: RummikubState): boolean => arrangementKey(setsOfCells(s.draft.cells)) !== arrangementKey(s.table);
/** Anything moved at all. */
const draftMoved = (s: RummikubState): boolean => cellsKey(s.draft.cells) !== cellsKey(startCells(s));
const resetDraft = (s: RummikubState): void => {
s.draft = { cells: startCells(s), edits: 0 };
};
function totalGames(o: RummikubOptions, players: number): number {
return o.gamesPerMatch === 'players' ? players : Number(o.gamesPerMatch);
}
/** C1–C3 (§8.2): tiles come from the start table or my rack, no duplicates, table tiles stay, first-meld rule. */
function conserve(s: RummikubState, p: PlayerId, sets: readonly DraftSet[]): string | null {
/**
* Loose check of a working table (§8.2 C1–C3): every tile from the start table or my rack, once, on its own cell,
* table tiles never back to the rack, and before the first meld the table tiles stay where they are.
*/
function conserve(s: RummikubState, p: PlayerId, cells: readonly Cell[]): string | null {
const start = tableTiles(s);
const rack = new Set(s.racks[p] ?? []);
const seen = new Set<string>();
for (const d of sets) {
if (d.tileIds.length === 0) return '빈 묶음이 있어요.';
for (const id of d.tileIds) {
if (seen.has(id)) return '같은 타일이 두 번 들어 있어요.';
seen.add(id);
if (!start.has(id) && !rack.has(id)) return '내 받침대나 바닥에 없는 타일이에요.';
}
const spots = new Set<number>();
for (const x of cells) {
if (seen.has(x.id)) return '같은 타일이 두 번 들어 있어요.';
seen.add(x.id);
if (!start.has(x.id) && !rack.has(x.id)) return '내 받침대나 바닥에 없는 타일이에요.';
if (!inBoard(x.r, x.c)) return '바닥 밖에는 놓을 수 없어요.';
const k = cellKey(x.r, x.c);
if (spots.has(k)) return '한 칸에 타일 두 개를 놓을 수 없어요.';
spots.add(k);
}
for (const id of start) if (!seen.has(id)) return '바닥의 타일은 내 받침대로 가져올 수 없어요.';
if (!s.hasMelded[p] && !s.options.initialMeldAllowExtend) {
const keys = new Set(sets.map((d) => [...d.tileIds].sort().join(',')));
for (const t of s.table) if (!keys.has([...t.tileIds].sort().join(','))) return '첫 등록 전에는 바닥의 타일을 옮길 수 없어요.';
const at = new Map(cells.map((x) => [x.id, cellKey(x.r, x.c)]));
for (const x of startCells(s)) if (at.get(x.id) !== cellKey(x.r, x.c)) return '첫 등록 전에는 바닥의 타일을 옮길 수 없어요.';
}
return null;
}
type TurnOutcome = { ok: true; normalized: NormalSet[]; fromRack: string[]; meldPoints: number } | { ok: false; reason: string; invalidIdx: number[]; meldPoints: number; fromRack: string[] };
type TurnOutcome =
| { ok: true; strips: Strip[]; normalized: NormalSet[]; fromRack: string[]; meldPoints: number }
| { ok: false; reason: string; invalidIdx: number[]; meldPoints: number; fromRack: string[] };
/** Turn commit validation (§8.2 validateTurn), shared by commit, timeout and the live check in the view. */
function validateTurn(s: RummikubState, p: PlayerId, sets: readonly DraftSet[], pre?: (NormalSet | null)[]): TurnOutcome {
function validateTurn(s: RummikubState, p: PlayerId, cells: readonly Cell[], pre?: { strips: Strip[]; norms: (NormalSet | null)[] }): TurnOutcome {
const start = tableTiles(s);
const fromRack = sets.flatMap((d) => d.tileIds).filter((id) => !start.has(id));
const normalized = pre ?? sets.map(normalizeSet);
const newOnly = normalized.filter((n, i) => n && sets[i]!.tileIds.every((id) => !start.has(id))) as NormalSet[];
const strips = pre?.strips ?? stripsOf(cells);
const normalized = pre?.norms ?? strips.map((x) => normalizeSet({ tileIds: x.tileIds }));
const fromRack = cells.map((x) => x.id).filter((id) => !start.has(id));
const newOnly = normalized.filter((n, i) => n && strips[i]!.tileIds.every((id) => !start.has(id))) as NormalSet[];
const meldPoints = newOnly.reduce((a, n) => a + n.points, 0);
const bad = (reason: string, invalidIdx: number[] = []): TurnOutcome => ({ ok: false, reason, invalidIdx, meldPoints, fromRack });
const c = conserve(s, p, sets);
const c = conserve(s, p, cells);
if (c) return bad(c);
if (fromRack.length === 0) return bad('받침대에서 타일을 1개 이상 내야 해요.');
const invalidIdx = normalized.flatMap((n, i) => (n ? [] : [i]));
if (invalidIdx.length) return bad('빨간 표시된 묶음을 고쳐 주세요.', invalidIdx);
if (!s.hasMelded[p]) {
if (!s.options.initialMeldAllowExtend) {
// The table sets must be exactly as they were: nothing added next to them.
const key = (ids: readonly string[]) => [...ids].sort().join(',');
const tableKeys = new Set(s.table.map((t) => key(t.tileIds)));
const idx = strips.flatMap((x, i) => (x.tileIds.some((id) => start.has(id)) && !tableKeys.has(key(x.tileIds)) ? [i] : []));
if (idx.length) return bad('첫 등록 전에는 바닥 묶음에 붙일 수 없어요. 한 칸 띄워 따로 놓아 주세요.', idx);
}
const min = s.options.initialMeldPoints;
if (meldPoints < min) return bad(`첫 등록은 ${min}점 이상이어야 해요 (지금 ${meldPoints}점).`);
}
return { ok: true, normalized: normalized as NormalSet[], fromRack, meldPoints };
return { ok: true, strips, normalized: normalized as NormalSet[], fromRack, meldPoints };
}
/** New table from normalized sets; ids are inherited from the old set with the biggest overlap. */
function buildTable(s: RummikubState, normalized: NormalSet[]): { table: TableSet[]; changed: string[] } {
/** New table from normalized sets at their strips; ids are inherited from the old set with the biggest overlap. */
function buildTable(s: RummikubState, out: Extract<TurnOutcome, { ok: true }>): { table: TableSet[]; changed: string[] } {
const taken = new Set<string>();
const changed: string[] = [];
const table = normalized.map((n) => {
const table = out.normalized.map((n, i) => {
const strip = out.strips[i]!;
let best: TableSet | null = null;
let bestOverlap = 0;
for (const t of s.table) {
@@ -302,7 +363,8 @@ function buildTable(s: RummikubState, normalized: NormalSet[]): { table: TableSe
id = `s${s.nextSetId++}`;
changed.push(id);
}
return { id, tileIds: n.tileIds, kind: n.kind, jokerAs: n.jokerAs };
// The set keeps its strip; runs are written in ascending order (the server's reading of the jokers).
return { id, tileIds: n.tileIds, kind: n.kind, jokerAs: n.jokerAs, r: strip.r, c: strip.c };
});
return { table, changed };
}
@@ -322,7 +384,7 @@ function startTurn(s: RummikubState, p: PlayerId, now: number): void {
s.current = p;
s.turnNo += 1;
s.turnStartedAt = now;
s.draft = { sets: startSets(s), history: [], edits: 0 };
resetDraft(s);
}
function nextPlayer(s: RummikubState, from: PlayerId): PlayerId {
@@ -335,9 +397,9 @@ function nextPlayer(s: RummikubState, from: PlayerId): PlayerId {
return from;
}
/** Turn ended without placing tiles: draw `count` (if the pool has any) or count it as a pass (§5.8). */
/** Turn ended without placing tiles: the table goes back, draw `count` (if the pool has any) or it counts as a pass (§5.8). */
function endWithoutPlay(s: RummikubState, p: PlayerId, count: number, kind: MoveKind, now: number, events: GameEvent[]): void {
s.draft = { sets: startSets(s), history: [], edits: 0 };
resetDraft(s);
const got = drawTiles(s, p, count);
s.lastDrawn[p] = got;
s.lastChanged = [];
@@ -357,7 +419,7 @@ function endWithoutPlay(s: RummikubState, p: PlayerId, count: number, kind: Move
}
function commitTurn(s: RummikubState, p: PlayerId, out: Extract<TurnOutcome, { ok: true }>, kind: MoveKind, now: number, events: GameEvent[]): void {
const { table, changed } = buildTable(s, out.normalized);
const { table, changed } = buildTable(s, out);
s.table = table;
const placed = new Set(out.fromRack);
s.racks[p] = s.racks[p]!.filter((id) => !placed.has(id));
@@ -425,7 +487,7 @@ function endRound(s: RummikubState, reason: 'rackEmpty' | 'stalemate', by: Playe
const revealed: Record<PlayerId, string[]> = {};
for (const p of players) revealed[p] = [...s.racks[p]!];
s.round = { gameNo: s.match.gameNo, endReason: reason, winners, scores, rackValues, revealed, ranking: rankByScore(players, winners, scores) };
s.draft = { sets: startSets(s), history: [], edits: 0 };
resetDraft(s);
events.push({ type: 'roundEnded', reason, winners, scores });
if (s.match.gameNo >= s.match.total || eligible.length < 2) finishMatch(s, eligible.length < 2 ? 'abandoned' : 'normal');
else {
@@ -513,21 +575,47 @@ function setupRound(s: RummikubState, rng: Rng, now: number): void {
startTurn(s, first, now);
}
function describeSet(d: DraftSet, n: NormalSet | null): DraftSetView {
// Only one number tile + jokers can be read both as a run and as a group.
const ambiguous = !!n && d.tileIds.length <= 4 && d.tileIds.filter((id) => !isJoker(id)).length === 1;
function describeGroup(x: Strip, n: NormalSet | null): GroupView {
return {
tileIds: d.tileIds,
...(d.as ? { as: d.as } : {}),
tileIds: x.tileIds,
r: x.r,
c: x.c,
ok: !!n,
problem: n ? null : setProblem(d),
problem: n ? null : setProblem({ tileIds: x.tileIds }),
kind: n?.kind ?? null,
jokerAs: n?.jokerAs ?? {},
points: n?.points ?? 0,
ambiguous,
};
}
/** The table cells a player would have after adding `sets` (whole sets, laid out like a computer would). */
function cellsFor(s: RummikubState, sets: readonly (readonly string[])[]): Cell[] | null {
const strips = layoutSets(sets, s.table);
return strips ? cellsOf(strips) : null;
}
/**
* Saves from before the grid (stateVersion 1): table sets get grid places, the working table its sets laid out the
* same way (the step-by-step undo history is dropped). Also tolerates a half-migrated state.
*/
function migrateV1(old: unknown): RummikubState {
const s = old as RummikubState & { table: (Omit<TableSet, 'r' | 'c'> & { r?: number; c?: number })[]; draft: { cells?: Cell[]; sets?: DraftSet[]; edits?: number } };
s.options = rummikubOptionsSchema.parse({ ...s.options });
if (s.table.some((t) => t.r === undefined || t.c === undefined)) {
const strips = layoutSets(s.table.map((t) => t.tileIds)) ?? [];
s.table = s.table.map((t, i) => ({ ...t, r: strips[i]?.r ?? 0, c: strips[i]?.c ?? 0 }));
}
const d = s.draft ?? {};
let cells: Cell[] | null = Array.isArray(d.cells) ? d.cells : null;
if (!cells && Array.isArray(d.sets)) {
const strips = layoutSets(d.sets.map((x) => x.tileIds), s.table as TableSet[]);
cells = strips ? cellsOf(strips) : null;
}
const st = s as RummikubState;
st.draft = { cells: cells ?? startCells(st), edits: d.edits ?? 0 };
return st;
}
// ---------------------------------------------------------------- definition
export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubView, RummikubOptions> = {
@@ -535,7 +623,7 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
nameKo: '루미큐브',
minPlayers: 2,
maxPlayers: 4,
stateVersion: 1,
stateVersion: 2,
defaultOptions: rummikubOptionsSchema.parse({}),
optionsSchema: rummikubOptionsSchema,
actionSchema: rummikubActionSchema as z.ZodType<RummikubAction>,
@@ -554,7 +642,7 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
current: players[0]!,
turnNo: 0,
turnStartedAt: now,
draft: { sets: [], history: [], edits: 0 },
draft: { cells: [], edits: 0 },
timeoutsInRow: Object.fromEntries(players.map((p) => [p, 0])),
consecutivePasses: 0,
lastDrawn: {},
@@ -582,26 +670,32 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
if (s.phase === 'finished') return fail('게임이 이미 끝났어요.');
if (a.type === 'leave') return s.left.includes(actor) ? fail('이미 나간 플레이어예요.') : ok;
if (s.left.includes(actor)) return fail('방을 나간 플레이어예요.');
// A late drag preview (the turn just ended) is dropped silently in apply, not answered with an error.
if (a.type === 'drag') return ok;
if (s.phase === 'roundEnd') {
if (a.type !== 'ready' && a.type !== 'timeout') return fail('다음 판을 기다리는 중이에요.');
return s.ready.includes(actor) ? fail('이미 준비했어요.') : ok;
}
if (a.type === 'ready') return fail('지금은 할 수 없어요.');
if (actor !== s.current) return fail('지금은 내 차례가 아니에요.');
if ((a.type === 'setDraft' || a.type === 'commit') && a.turn !== undefined && a.turn !== s.turnNo) return fail('지난 차례의 요청이라 무시했어요.');
if ((a.type === 'arrange' || a.type === 'commit') && a.turn !== undefined && a.turn !== s.turnNo) return fail('지난 차례의 요청이라 무시했어요.');
switch (a.type) {
case 'setDraft': {
const err = conserve(s, actor, a.sets);
case 'arrange': {
const err = conserve(s, actor, a.cells);
return err ? fail(err) : ok;
}
case 'undoDraft':
return s.draft.history.length ? ok : fail('되돌릴 것이 없어요.');
case 'resetDraft':
return ok;
case 'commit': {
const r = validateTurn(s, actor, s.draft.sets);
if (a.cells) {
const err = conserve(s, actor, a.cells);
if (err) return fail(err);
}
const cells = a.cells ?? s.draft.cells;
const r = validateTurn(s, actor, cells);
if (r.ok) return ok;
if (s.options.invalidCommitPenalty === 'reject' || !draftChanged(s) || r.fromRack.length === 0) return fail(r.reason);
const changed = arrangementKey(setsOfCells(cells)) !== arrangementKey(s.table);
if (s.options.invalidCommitPenalty === 'reject' || !changed || r.fromRack.length === 0) return fail(r.reason);
return ok;
}
case 'draw':
@@ -614,6 +708,16 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
},
apply(prev, actor, a, { rng, now }) {
if (a.type === 'drag') {
// Stream action: the state does not change; the event goes to everybody (tiles not on the table yet hidden).
const s = prev;
if (s.phase !== 'playing' || actor !== s.current || !s.options.showDraftToOthers || (a.turn !== undefined && a.turn !== s.turnNo)) return { state: prev, events: [] };
const onBoard = new Set(s.draft.cells.map((x) => x.id));
const rack = new Set(s.racks[actor] ?? []);
const tiles = a.ids.filter((id) => onBoard.has(id) || rack.has(id)).map((id) => (onBoard.has(id) ? id : null));
const ev: DragEvent = { type: 'drag', player: actor, turn: s.turnNo, tiles, x: a.x, y: a.y };
return { state: prev, events: [ev as unknown as GameEvent] };
}
// The state is plain JSON by contract; this is much faster than structuredClone.
const s = JSON.parse(JSON.stringify(prev)) as RummikubState;
const events: GameEvent[] = [];
@@ -627,7 +731,7 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
else if (s.seats.every((p) => s.ready.includes(p))) setupRound(s, rng, now);
} else if (activeSeats(s).length < 2) {
// Nobody left to play against: the match ends without scoring this round.
s.draft = { sets: startSets(s), history: [], edits: 0 };
resetDraft(s);
finishMatch(s, 'abandoned');
} else if (s.current === actor) {
pushLog(s, actor, 'left', 0);
@@ -641,26 +745,17 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
return { state: s, events };
}
switch (a.type) {
case 'setDraft':
s.draft.history.push(s.draft.sets);
if (s.draft.history.length > HISTORY_MAX) s.draft.history.shift();
s.draft.sets = a.sets.map(cleanSet);
s.draft.edits += 1;
break;
case 'undoDraft':
s.draft.sets = s.draft.history.pop()!;
case 'arrange':
s.draft.cells = a.cells.map((x) => ({ id: x.id, r: x.r, c: x.c }));
s.draft.edits += 1;
break;
case 'resetDraft':
if (draftChanged(s)) {
s.draft.history.push(s.draft.sets);
if (s.draft.history.length > HISTORY_MAX) s.draft.history.shift();
}
s.draft.sets = startSets(s);
s.draft.edits += 1;
if (draftMoved(s)) s.draft.edits += 1;
s.draft.cells = startCells(s);
break;
case 'commit': {
const r = validateTurn(s, actor, s.draft.sets);
if (a.cells) s.draft.cells = a.cells.map((x) => ({ id: x.id, r: x.r, c: x.c }));
const r = validateTurn(s, actor, s.draft.cells);
if (r.ok) commitTurn(s, actor, r, 'commit', now, events);
else endWithoutPlay(s, actor, 3, 'penalty', now, events);
break;
@@ -676,14 +771,18 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
endWithoutPlay(s, actor, 1, 'timeoutDraw', now, events);
break;
}
const r = validateTurn(s, actor, s.draft.sets);
const r = validateTurn(s, actor, s.draft.cells);
if (r.ok) {
// App rule (default): the turn is not finished until 완료, so even a valid table goes back (§5.7).
if (s.options.timeoutValidDraft === 'commit') commitTurn(s, actor, r, 'timeoutCommit', now, events);
else endWithoutPlay(s, actor, 1, 'timeoutDraw', now, events);
} else if (r.fromRack.length === 0 && r.invalidIdx.length === 0) {
// Only rearranged (or nothing from the rack): put it back, no penalty.
endWithoutPlay(s, actor, 1, 'timeoutDraw', now, events);
} else endWithoutPlay(s, actor, s.options.invalidTimeoutPenalty, 'penalty', now, events);
} else {
const n = s.options.invalidTimeoutPenalty;
endWithoutPlay(s, actor, n, n > 1 ? 'penalty' : 'timeoutDraw', now, events);
}
break;
}
}
@@ -695,10 +794,11 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
const playing = s.phase === 'playing';
const isCur = playing && me === s.current;
const draftVisible = playing && (isCur || s.options.showDraftToOthers);
const norms = draftVisible ? s.draft.sets.map(normalizeSet) : [];
const strips = draftVisible ? stripsOf(s.draft.cells) : [];
const norms = strips.map((x) => normalizeSet({ tileIds: x.tileIds }));
let check: TurnCheck | null = null;
if (isCur) {
const r = validateTurn(s, me, s.draft.sets, norms);
const r = validateTurn(s, me, s.draft.cells, { strips, norms });
check = r.ok
? { ok: true, reason: null, invalidIdx: [], meldPoints: r.meldPoints, fromRack: r.fromRack.length }
: { ok: false, reason: r.reason, invalidIdx: r.invalidIdx, meldPoints: r.meldPoints, fromRack: r.fromRack.length };
@@ -725,15 +825,14 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
lastChanged: s.lastChanged,
log: s.log,
draftEdits: playing ? s.draft.edits : 0,
draft: draftVisible ? s.draft.sets.map((d, i) => describeSet(d, norms[i] ?? null)) : null,
draft: draftVisible ? { cells: s.draft.cells, groups: strips.map((x, i) => describeGroup(x, norms[i] ?? null)) } : null,
me,
my: me
? {
rack: s.racks[me] ?? [],
lastDrawn: s.lastDrawn[me] ?? [],
melded: !!s.hasMelded[me],
canUndo: isCur && s.draft.history.length > 0,
changed: isCur && draftChanged(s),
changed: isCur && draftMoved(s),
check,
needReady: s.phase === 'roundEnd' && !s.ready.includes(me) && !s.left.includes(me),
}
@@ -748,6 +847,10 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
};
},
isStreamAction(a) {
return a.type === 'drag';
},
activePlayers(s) {
if (s.phase === 'playing') return [s.current];
if (s.phase === 'roundEnd') return s.seats.filter((p) => !s.ready.includes(p) && !s.left.includes(p));
@@ -783,15 +886,20 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
};
},
/** Test helper: draw / play rack-only sets / extend a table set / an invalid try, then commit or undo. */
/** v1 (sets without grid places) → v2 (grid). */
migrate(old, fromVersion) {
return fromVersion < 2 ? migrateV1(old) : (old as RummikubState);
},
/** Test helper: draw / lay out rack-only sets / extend a table set / an invalid try, then commit or reset. */
legalActions(s, p) {
if (!s.seats.includes(p) || s.left.includes(p) || s.phase === 'finished') return [];
if (s.phase === 'roundEnd') return s.ready.includes(p) ? [] : [{ type: 'ready' }];
if (p !== s.current) return [];
const acts: RummikubAction[] = [];
if (draftChanged(s)) {
const r = validateTurn(s, p, s.draft.sets);
if (r.ok) acts.push(s.draft.edits % 4 === 3 ? { type: 'undoDraft' } : { type: 'commit' });
const r = validateTurn(s, p, s.draft.cells);
if (r.ok) acts.push(s.draft.edits % 4 === 3 ? { type: 'resetDraft' } : { type: 'commit' });
else {
acts.push({ type: 'resetDraft' }, { type: 'draw' });
if (s.options.invalidCommitPenalty === 'penalty3' && r.fromRack.length > 0) acts.push({ type: 'commit' });
@@ -800,42 +908,50 @@ export const rummikub: GameDefinition<RummikubState, RummikubAction, RummikubVie
}
const drawAct: RummikubAction = s.pool.length ? { type: 'draw' } : { type: 'pass' };
const rack = s.racks[p]!;
const base = startSets(s);
const base = s.table.map((t) => t.tileIds);
const push = (sets: string[][], direct = false) => {
const cells = cellsFor(s, sets);
if (cells) acts.push(direct ? { type: 'commit', cells } : { type: 'arrange', cells });
};
if (!s.hasMelded[p]) {
const meld = findMeld(rack, s.options.initialMeldPoints);
if (meld) acts.push({ type: 'setDraft', sets: [...base, ...meld.map((m) => ({ tileIds: m.tileIds }))] });
if (meld) push([...base, ...meld.map((m) => m.tileIds)], s.turnNo % 2 === 0);
} else {
// Everything playable at once: disjoint rack sets, then single tiles added to any set that accepts them.
const all: { tileIds: string[]; kind: 'run' | 'group'; jokerAs: Record<string, JokerAs> }[] = [...s.table, ...pickDisjoint(rack).sets];
const used = new Set(all.flatMap((d) => d.tileIds));
let firstExt: DraftSet[] | null = null;
let firstExt: string[][] | null = null;
for (const id of rack) {
if (used.has(id)) continue;
for (let i = 0; i < all.length; i++) {
const ext = extendSet(all[i]!, id);
if (!ext) continue;
if (!firstExt && i < base.length) firstExt = base.map((d, k) => (k === i ? { tileIds: ext.tileIds } : d));
if (!firstExt && i < base.length) firstExt = base.map((d, k) => (k === i ? ext.tileIds : d));
all[i] = ext;
used.add(id);
break;
}
}
if (all.length !== base.length || firstExt) acts.push({ type: 'setDraft', sets: all.map((d) => ({ tileIds: d.tileIds })) });
if (all.length !== base.length || firstExt) push(all.map((d) => d.tileIds), s.turnNo % 2 === 0);
// Rearrangement only: one rack tile added to an existing table set.
if (firstExt) acts.push({ type: 'setDraft', sets: firstExt });
if (firstExt) push(firstExt);
}
if (!acts.length || s.turnNo % 3 === 0) acts.push(drawAct);
// An unfinished try (single tile) now and then, to exercise invalid commit / timeout paths.
if (rack.length && s.turnNo % 7 === 0) acts.push({ type: 'setDraft', sets: [...base, { tileIds: [rack[0]!] }] });
if (rack.length && s.turnNo % 7 === 0) {
const cells = startCells(s);
const spot = freeSpot(cells, 1);
if (spot) acts.push({ type: 'arrange', cells: [...cells, { id: rack[0]!, ...spot }] });
}
return acts;
},
/** Hidden tiles of `player` (rack minus tiles already shown in a visible draft) plus the pool. */
/** Hidden tiles of `player` (rack minus tiles already shown on a visible working table) plus the pool. */
secretsOf(s, player) {
if (s.phase !== 'playing') return [...s.pool];
let rack = s.racks[player] ?? [];
if (s.options.showDraftToOthers && player === s.current) {
const shown = new Set(s.draft.sets.flatMap((d) => d.tileIds));
const shown = new Set(s.draft.cells.map((x) => x.id));
rack = rack.filter((id) => !shown.has(id));
}
return [...rack, ...s.pool];

View File

@@ -277,3 +277,134 @@ export function extendSet(set: Pick<NormalSet, 'tileIds' | 'kind' | 'jokerAs'>,
}
return cand ? normalizeSet({ tileIds: cand, as: set.kind }) : null;
}
// ---------------------------------------------------------------- table grid (§8.1)
/**
* The table is a grid like the app's: tiles side by side in a row (left to right) form one set, an empty cell ends
* it. 20 × 12 cells hold every possible table (106 tiles with the gaps; a 13-tile run fits in one row).
*/
export const BOARD_COLS = 20;
export const BOARD_ROWS = 12;
/** One tile on the grid. */
export interface Cell {
id: string;
r: number;
c: number;
}
/** A set on the grid: `tileIds` fill row `r` from column `c` to the right. */
export interface Strip {
tileIds: string[];
r: number;
c: number;
}
export const cellKey = (r: number, c: number): number => r * BOARD_COLS + c;
export const inBoard = (r: number, c: number): boolean => Number.isInteger(r) && Number.isInteger(c) && r >= 0 && r < BOARD_ROWS && c >= 0 && c < BOARD_COLS;
/** The sets on the grid, top row first, left to right; tile order = left to right. */
export function stripsOf(cells: readonly Cell[]): Strip[] {
const sorted = [...cells].sort((a, b) => a.r - b.r || a.c - b.c);
const out: Strip[] = [];
let cur: Strip | null = null;
for (const x of sorted) {
if (cur && cur.r === x.r && cur.c + cur.tileIds.length === x.c) cur.tileIds.push(x.id);
else {
cur = { tileIds: [x.id], r: x.r, c: x.c };
out.push(cur);
}
}
return out;
}
/** Cells of positioned sets. */
export function cellsOf(sets: readonly { tileIds: readonly string[]; r: number; c: number }[]): Cell[] {
return sets.flatMap((s) => s.tileIds.map((id, i) => ({ id, r: s.r, c: s.c + i })));
}
/** Order-insensitive key of exact positions (did anything move at all?). */
export function cellsKey(cells: readonly Cell[]): string {
return cells
.map((x) => `${x.id}@${x.r}.${x.c}`)
.sort()
.join(',');
}
/** Room for `n` tiles at (r, c): inside the grid, free, and an empty cell (or the edge) on both sides. */
function fits(taken: Set<number>, r: number, c: number, n: number): boolean {
if (r < 0 || r >= BOARD_ROWS || c < 0 || c + n > BOARD_COLS) return false;
for (let k = c - 1; k <= c + n; k++) if (k >= 0 && k < BOARD_COLS && taken.has(cellKey(r, k))) return false;
return true;
}
/** First free place for a set of `n` tiles (top row first), or null when the grid is full. */
export function freeSpot(cells: readonly Cell[], n: number): { r: number; c: number } | null {
const taken = new Set(cells.map((x) => cellKey(x.r, x.c)));
for (let r = 0; r < BOARD_ROWS; r++) for (let c = 0; c + n <= BOARD_COLS; c++) if (fits(taken, r, c, n)) return { r, c };
return null;
}
/**
* Positions for whole sets (computer players, legacy saves, test helpers). A set that keeps tiles of a positioned
* set in `prev` stays where those tiles were when there is room (so extending a run only adds tiles at its end);
* the rest go to the first free place. null when they do not fit.
*/
export function layoutSets(sets: readonly (readonly string[])[], prev: readonly Strip[] = []): Strip[] | null {
const where = new Map<string, { s: number; i: number }>();
prev.forEach((p, s) => p.tileIds.forEach((id, i) => where.set(id, { s, i })));
const taken = new Set<number>();
const out: (Strip | null)[] = sets.map(() => null);
const anchor = (ids: readonly string[]): { r: number; c: number; overlap: number } | null => {
const counts = new Map<number, number>();
for (const id of ids) {
const w = where.get(id);
if (w) counts.set(w.s, (counts.get(w.s) ?? 0) + 1);
}
let best = -1;
let overlap = 0;
for (const [s, n] of counts) if (n > overlap) [best, overlap] = [s, n];
if (best < 0) return null;
const k = ids.findIndex((id) => where.get(id)?.s === best);
const p = prev[best]!;
return { r: p.r, c: p.c + where.get(ids[k]!)!.i - k, overlap };
};
const anchored = sets.map((ids, i) => ({ i, a: anchor(ids) })).filter((x) => x.a).sort((x, y) => y.a!.overlap - x.a!.overlap);
for (const { i, a } of anchored) {
const n = sets[i]!.length;
if (!fits(taken, a!.r, a!.c, n)) continue;
out[i] = { tileIds: [...sets[i]!], r: a!.r, c: a!.c };
for (let k = 0; k < n; k++) taken.add(cellKey(a!.r, a!.c + k));
}
for (let i = 0; i < sets.length; i++) {
if (out[i]) continue;
const n = sets[i]!.length;
let spot: { r: number; c: number } | null = null;
for (let r = 0; r < BOARD_ROWS && !spot; r++) for (let c = 0; c + n <= BOARD_COLS && !spot; c++) if (fits(taken, r, c, n)) spot = { r, c };
if (!spot) return null;
out[i] = { tileIds: [...sets[i]!], ...spot };
for (let k = 0; k < n; k++) taken.add(cellKey(spot.r, spot.c + k));
}
return out as Strip[];
}
/**
* Drops `ids` (in this order, left to right) so the first one lands on (r, c) — the drag-and-drop / tap placement.
* Other tiles in the way are pushed right together with everything right of them in that row (inserting into a
* set). Tiles that are not in `cells` yet come from the rack. null when the row has no room.
*/
export function placeTiles(cells: readonly Cell[], ids: readonly string[], r: number, c: number): Cell[] | null {
const n = ids.length;
if (n === 0 || n > BOARD_COLS || r < 0 || r >= BOARD_ROWS) return null;
const moving = new Set(ids);
let rest = cells.filter((x) => !moving.has(x.id));
const c0 = Math.max(0, Math.min(c, BOARD_COLS - n));
const blocked = rest.some((x) => x.r === r && x.c >= c0 && x.c < c0 + n);
if (blocked) {
const right = rest.filter((x) => x.r === r && x.c >= c0);
if (right.some((x) => x.c + n >= BOARD_COLS)) return null;
rest = rest.map((x) => (x.r === r && x.c >= c0 ? { ...x, c: x.c + n } : x));
}
return [...rest, ...ids.map((id, i) => ({ id, r, c: c0 + i }))];
}

View File

@@ -2,14 +2,20 @@ import { describe, expect, test } from 'bun:test';
import { SeededRng, playoutSeeds, randomPlayout, seedN, type GameEvent, type PlayerId } from '@bg/engine';
import {
ALL_TILE_IDS,
BOARD_COLS,
BOARD_ROWS,
cellsOf,
findMeld,
layoutSets,
normalizeSet,
placeTiles,
rummikub,
scoreRound,
setProblem,
sortTiles,
stripsOf,
tileCount,
type DraftSet,
type Cell,
type RummikubAction,
type RummikubOptions,
type RummikubState,
@@ -26,8 +32,8 @@ function mk(opts: Partial<RummikubOptions> = {}, players = ['A', 'B'], seed = 1)
}
/**
* Puts the game into a hand-made position: given racks and table sets, everything else goes to the pool
* (in id order), `current` has the turn with a fresh draft.
* Puts the game into a hand-made position: given racks and table sets (laid out on the grid), everything else goes
* to the pool (in id order), `current` has the turn with a fresh working table.
*/
function rig(
s: RummikubState,
@@ -36,10 +42,11 @@ function rig(
const table = o.table ?? [];
const used = new Set([...Object.values(o.racks).flat(), ...table.flat()]);
s.racks = Object.fromEntries(s.roundPlayers.map((p) => [p, [...(o.racks[p] ?? [])]]));
const strips = layoutSets(table)!;
s.table = table.map((ids, i) => {
const n = normalizeSet({ tileIds: ids });
if (!n) throw new Error(`rig: invalid table set ${ids}`);
return { id: `s${i + 1}`, tileIds: n.tileIds, kind: n.kind, jokerAs: n.jokerAs };
return { id: `s${i + 1}`, tileIds: n.tileIds, kind: n.kind, jokerAs: n.jokerAs, r: strips[i]!.r, c: strips[i]!.c };
});
s.nextSetId = table.length + 1;
const rest = ALL_TILE_IDS.filter((id) => !used.has(id));
@@ -51,7 +58,7 @@ function rig(
}
s.current = o.current ?? s.roundPlayers[0]!;
s.hasMelded = Object.fromEntries(s.roundPlayers.map((p) => [p, (o.melded ?? []).includes(p)]));
s.draft = { sets: s.table.map((t) => ({ tileIds: [...t.tileIds], as: t.kind })), history: [], edits: 0 };
s.draft = { cells: cellsOf(s.table), edits: 0 };
s.consecutivePasses = 0;
expect(tileCount(s)).toBe(106);
return s;
@@ -61,6 +68,8 @@ function act(s: RummikubState, who: PlayerId, a: RummikubAction): RummikubState
return actE(s, who, a).state;
}
function actE(s: RummikubState, who: PlayerId, a: RummikubAction): { state: RummikubState; events: GameEvent[] } {
const parsed = rummikub.actionSchema.safeParse(a);
if (!parsed.success && a.type !== 'timeout' && a.type !== 'leave') throw new Error(`schema rejects ${JSON.stringify(a)}`);
const v = rummikub.validate(s, who, a);
if (!v.ok) throw new Error(`${who} ${JSON.stringify(a)} rejected: ${v.reason}`);
clock += 1000;
@@ -73,10 +82,13 @@ function reason(s: RummikubState, who: PlayerId, a: RummikubAction): string {
if (v.ok) throw new Error(`expected rejection of ${JSON.stringify(a)}`);
return v.reason;
}
const tableSets = (s: RummikubState): DraftSet[] => s.table.map((t) => ({ tileIds: [...t.tileIds] }));
/** Grid cells for whole sets: table sets keep their places, new ones go to the first free place. */
const lay = (s: RummikubState, sets: string[][]): Cell[] => cellsOf(layoutSets(sets, s.table)!);
const tableSets = (s: RummikubState): string[][] => s.table.map((t) => [...t.tileIds]);
const setsOf = (s: RummikubState) => s.table.map((t) => t.tileIds);
/** Sets the draft and commits in one go. */
const play = (s: RummikubState, who: PlayerId, sets: string[][]) => act(act(s, who, { type: 'setDraft', sets: sets.map((tileIds) => ({ tileIds })) }), who, { type: 'commit' });
const arrange = (s: RummikubState, who: PlayerId, sets: string[][]) => act(s, who, { type: 'arrange', cells: lay(s, sets) });
/** Lays the sets out and commits in one go. */
const play = (s: RummikubState, who: PlayerId, sets: string[][]) => act(arrange(s, who, sets), who, { type: 'commit' });
// ---------------------------------------------------------------- setup
@@ -101,6 +113,7 @@ describe('셋업 (§4)', () => {
expect(tileCount(s)).toBe(106);
expect(new Set([...s.pool, ...Object.values(s.racks).flat()]).size).toBe(106);
expect(s.table).toEqual([]);
expect(s.draft).toEqual({ cells: [], edits: 0 });
});
test('same seed → same deal and first player; the opening draw picks the highest number', () => {
@@ -178,12 +191,66 @@ describe('세트 판정 (§5.1)', () => {
});
});
// ---------------------------------------------------------------- grid
describe('바닥 칸 (§8.1)', () => {
test('tiles side by side in a row are one set; an empty cell or a new row starts another', () => {
const cells: Cell[] = [
{ id: 'R5a', r: 0, c: 3 },
{ id: 'R3a', r: 0, c: 1 },
{ id: 'R4a', r: 0, c: 2 },
{ id: 'K7a', r: 0, c: 5 },
{ id: 'B7a', r: 1, c: 0 },
];
expect(stripsOf(cells)).toEqual([
{ tileIds: ['R3a', 'R4a', 'R5a'], r: 0, c: 1 },
{ tileIds: ['K7a'], r: 0, c: 5 },
{ tileIds: ['B7a'], r: 1, c: 0 },
]);
});
test('placeTiles: drop on an empty cell, next to a set (joins it), or onto a tile (pushes the rest of the row right)', () => {
const run: Cell[] = cellsOf([{ tileIds: ['R4a', 'R5a', 'R6a'], r: 0, c: 0 }, { tileIds: ['K9a', 'B9a', 'O9a'], r: 0, c: 5 }]);
// Next to the run: it becomes R4-R7.
expect(stripsOf(placeTiles(run, ['R7a'], 0, 3)!)[0]).toEqual({ tileIds: ['R4a', 'R5a', 'R6a', 'R7a'], r: 0, c: 0 });
// Onto R6: R6 and everything right of it moves one cell right (inserting).
const ins = placeTiles(run, ['JK1'], 0, 2)!;
expect(stripsOf(ins).map((x) => x.tileIds)).toEqual([['R4a', 'R5a', 'JK1', 'R6a'], ['K9a', 'B9a', 'O9a']]);
expect(ins.find((x) => x.id === 'K9a')).toEqual({ id: 'K9a', r: 0, c: 6 });
// Several tiles keep their order; near the right edge they are pulled back inside.
expect(placeTiles([], ['B1a', 'B2a', 'B3a'], 2, BOARD_COLS - 1)).toEqual([
{ id: 'B1a', r: 2, c: BOARD_COLS - 3 },
{ id: 'B2a', r: 2, c: BOARD_COLS - 2 },
{ id: 'B3a', r: 2, c: BOARD_COLS - 1 },
]);
// Moving a tile within the board: it leaves its old cell.
const moved = placeTiles(run, ['R6a'], 3, 0)!;
expect(moved.filter((x) => x.id === 'R6a')).toEqual([{ id: 'R6a', r: 3, c: 0 }]);
// No room to push: null.
const full = cellsOf([{ tileIds: Array.from({ length: 13 }, (_, i) => `O${i + 1}a`), r: 0, c: BOARD_COLS - 13 }]);
expect(placeTiles(full, ['K1a'], 0, BOARD_COLS - 13)).toBeNull();
expect(placeTiles(full, ['K1a'], BOARD_ROWS, 0)).toBeNull();
});
test('layoutSets keeps sets in place, extends at the ends, puts new sets in free places with a gap', () => {
const prev = [{ tileIds: ['R5a', 'R6a', 'R7a'], r: 0, c: 4 }];
const out = layoutSets([['R4a', 'R5a', 'R6a', 'R7a'], ['K1a', 'K2a', 'K3a']], prev)!;
expect(out[0]).toEqual({ tileIds: ['R4a', 'R5a', 'R6a', 'R7a'], r: 0, c: 3 });
expect(out[1]).toEqual({ tileIds: ['K1a', 'K2a', 'K3a'], r: 0, c: 8 });
// Every possible table fits: 35 sets of three and ten runs of ten.
const threes = Array.from({ length: 35 }, (_, i) => [`a${i}`, `b${i}`, `c${i}`]);
expect(layoutSets(threes)).not.toBeNull();
const tens = Array.from({ length: 10 }, (_, i) => Array.from({ length: 10 }, (_, k) => `t${i}-${k}`));
expect(layoutSets(tens)).not.toBeNull();
});
});
// ---------------------------------------------------------------- first meld
describe('첫 등록 (§5.3)', () => {
test('30 points from rack tiles only; 21 points is refused with the current total', () => {
let s = rig(mk(), { racks: { A: ['R10a', 'R11a', 'R12a', 'K5a'], B: ['B1a', 'B2a', 'B3a', 'K5b', 'R5a', 'O5a'] }, current: 'B' });
s = act(s, 'B', { type: 'setDraft', sets: [{ tileIds: ['B1a', 'B2a', 'B3a'] }, { tileIds: ['K5b', 'R5a', 'O5a'] }] });
s = arrange(s, 'B', [['B1a', 'B2a', 'B3a'], ['K5b', 'R5a', 'O5a']]);
expect(reason(s, 'B', { type: 'commit' })).toBe('첫 등록은 30점 이상이어야 해요 (지금 21점).');
expect(rummikub.view(s, 'B').my!.check).toMatchObject({ ok: false, meldPoints: 21 });
s = act(s, 'B', { type: 'draw' });
@@ -193,30 +260,36 @@ describe('첫 등록 (§5.3)', () => {
expect(s.racks.A).toEqual(['K5a']);
});
test('joker position decides the first meld: [조커, 검정9, 검정10] = 27 refused, [검정9, 검정10, 조커] = 30 accepted', () => {
test('joker position on the grid decides the first meld: [조커, 검정9, 검정10] = 27 refused, [검정9, 검정10, 조커] = 30 accepted', () => {
let s = rig(mk(), { racks: { A: ['JK1', 'K9a', 'K10a', 'R1a'], B: ['B1a'] } });
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['JK1', 'K9a', 'K10a'] }] });
s = arrange(s, 'A', [['JK1', 'K9a', 'K10a']]);
expect(reason(s, 'A', { type: 'commit' })).toBe('첫 등록은 30점 이상이어야 해요 (지금 27점).');
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['K9a', 'K10a', 'JK1'] }] });
s = arrange(s, 'A', [['K9a', 'K10a', 'JK1']]);
s = act(s, 'A', { type: 'commit' });
expect(s.table[0]!.jokerAs).toEqual({ JK1: { color: 'K', n: 11 } });
});
test('before the first meld: touching or extending table sets is refused at setDraft (C3)', () => {
const s = rig(mk(), { racks: { A: ['R3a', 'K10a', 'B10a', 'O10a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a', 'R7a']], melded: ['B'] });
// Extend the table run with a rack tile.
expect(reason(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['R3a', 'R4a', 'R5a', 'R6a', 'R7a'] }] })).toBe('첫 등록 전에는 바닥의 타일을 옮길 수 없어요.');
// Split the table run.
expect(reason(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['R4a', 'R5a'] }, { tileIds: ['R6a', 'R7a'] }] })).toBe('첫 등록 전에는 바닥의 타일을 옮길 수 없어요.');
test('before the first meld: table tiles cannot move (arrange), and nothing may be added next to a table set (commit)', () => {
const s = rig(mk(), { racks: { A: ['R8a', 'K10a', 'B10a', 'O10a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a', 'R7a']], melded: ['B'] });
// Splitting the table run (moving R6, R7 away).
const split = placeTiles(s.draft.cells, ['R6a', 'R7a'], 2, 0)!;
expect(reason(s, 'A', { type: 'arrange', cells: split })).toBe('첫 등록 전에는 바닥의 타일을 옮길 수 없어요.');
// R8 right after the table run is fine while working, but cannot be committed, even with 30 points elsewhere.
let t = act(s, 'A', { type: 'arrange', cells: placeTiles(s.draft.cells, ['R8a'], 0, 4)! });
t = act(t, 'A', { type: 'arrange', cells: placeTiles(t.draft.cells, ['K10a', 'B10a', 'O10a'], 3, 0)! });
expect(reason(t, 'A', { type: 'commit' })).toBe('첫 등록 전에는 바닥 묶음에 붙일 수 없어요. 한 칸 띄워 따로 놓아 주세요.');
const v = rummikub.view(t, 'A');
expect(v.my!.check!.invalidIdx.map((i) => v.draft!.groups[i]!.tileIds)).toEqual([['R4a', 'R5a', 'R6a', 'R7a', 'R8a']]);
// A new set next to the untouched table set is fine.
const t = play(s, 'A', [['R4a', 'R5a', 'R6a', 'R7a'], ['K10a', 'B10a', 'O10a']]);
expect(t.hasMelded.A).toBe(true);
const u = play(s, 'A', [['R4a', 'R5a', 'R6a', 'R7a'], ['K10a', 'B10a', 'O10a']]);
expect(u.hasMelded.A).toBe(true);
expect(u.table.find((x) => x.tileIds.includes('R4a'))).toMatchObject({ r: s.table[0]!.r, c: s.table[0]!.c });
});
test('initialMeldAllowExtend: 30 from new sets first, then extending in the same turn is allowed', () => {
const base = { racks: { A: ['R3a', 'K10a', 'B10a', 'O10a', 'R8a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a', 'R7a']], melded: ['B'] };
let s = rig(mk({ initialMeldAllowExtend: true }), base);
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['R3a', 'R4a', 'R5a', 'R6a', 'R7a', 'R8a'] }] });
s = arrange(s, 'A', [['R3a', 'R4a', 'R5a', 'R6a', 'R7a', 'R8a']]);
expect(reason(s, 'A', { type: 'commit' })).toBe('첫 등록은 30점 이상이어야 해요 (지금 0점).');
s = play(s, 'A', [['R3a', 'R4a', 'R5a', 'R6a', 'R7a', 'R8a'], ['K10a', 'B10a', 'O10a']]);
expect(s.racks.A).toEqual([]);
@@ -241,6 +314,24 @@ describe('재배치와 조커 회수 (§5.4, §5.5)', () => {
expect(s.lastChanged.sort()).toEqual(['s1', 's2']);
});
test('the same split by dragging: R6 dropped onto R7 pushes R7-R8 right, then a gap is opened', () => {
let s = rig(mk(), { racks: { A: ['R6b', 'K1a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a', 'R7a', 'R8a']], melded: ['A'] });
const { r, c } = s.table[0]!;
// Drop R6b onto R7 → R4 R5 R6 R6b R7 R8; then move R6b R7 R8 one more to the right → R4 R5 R6 _ R6b R7 R8.
s = act(s, 'A', { type: 'arrange', cells: placeTiles(s.draft.cells, ['R6b'], r, c + 3)! });
expect(rummikub.view(s, 'A').draft!.groups.map((g) => g.ok)).toEqual([false]);
s = act(s, 'A', { type: 'arrange', cells: placeTiles(s.draft.cells, ['R6b', 'R7a', 'R8a'], r, c + 4)! });
expect(rummikub.view(s, 'A').draft!.groups.map((g) => g.tileIds)).toEqual([
['R4a', 'R5a', 'R6a'],
['R6b', 'R7a', 'R8a'],
]);
s = act(s, 'A', { type: 'commit' });
expect(s.table.map((t) => [t.c - c, t.tileIds.length])).toEqual([
[0, 3],
[4, 3],
]);
});
test('official examples: add 파랑3 to 파랑4-5-6, 4th colour to a group, take 파랑4 from a 4-group', () => {
let s = rig(mk(), {
racks: { A: ['B3a', 'O8a', 'B3b', 'B5b', 'B6b', 'K1a'], B: ['B1a'] },
@@ -252,77 +343,96 @@ describe('재배치와 조커 회수 (§5.4, §5.5)', () => {
expect(s.table).toHaveLength(4);
});
test('joker retrieval: [파랑5, 조커, 파랑7] + [파랑6, 검정3, 빨강3] → [파랑5,6,7] [검정3, 빨강3, 조커]', () => {
test('joker retrieval (§5.5): [파랑5, 조커, 파랑7] + [파랑6, 검정3, 빨강3] → [파랑5,6,7] [검정3, 빨강3, 조커]', () => {
let s = rig(mk(), { racks: { A: ['B6a', 'K3a', 'R3a', 'O1a'], B: ['B1a'] }, table: [['B5a', 'JK1', 'B7a']], melded: ['A'] });
// Taking the joker back to the rack is refused (C2).
expect(reason(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['B5a', 'B6a', 'B7a'] }] })).toBe('바닥의 타일은 내 받침대로 가져올 수 없어요.');
// Taking the joker back to the rack is refused (it must be used again on the table this turn).
const noJoker = lay(s, [['B5a', 'B6a', 'B7a']]);
expect(reason(s, 'A', { type: 'arrange', cells: noJoker })).toBe('바닥의 타일은 내 받침대로 가져올 수 없어요.');
expect(reason(s, 'A', { type: 'commit', cells: noJoker })).toBe('바닥의 타일은 내 받침대로 가져올 수 없어요.');
// The joker left on its own is not a valid set either.
const lonely = act(s, 'A', { type: 'arrange', cells: [...lay(s, [['B5a', 'B6a', 'B7a']]), { id: 'JK1', r: 5, c: 0 }] });
expect(reason(lonely, 'A', { type: 'commit' })).toBe('빨간 표시된 묶음을 고쳐 주세요.');
s = play(s, 'A', [['B5a', 'B6a', 'B7a'], ['K3a', 'R3a', 'JK1']]);
expect(setsOf(s)).toEqual([['B5a', 'B6a', 'B7a'], ['K3a', 'R3a', 'JK1']]);
expect(s.table[1]!.jokerAs).toEqual({ JK1: { color: null, n: 3 } });
expect(s.racks.A).toEqual(['O1a']);
});
test('rearranging without a rack tile is refused; leftover single tiles are refused', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a', 'R7a', 'R8a', 'R9a']], melded: ['A'] });
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['R4a', 'R5a', 'R6a'] }, { tileIds: ['R7a', 'R8a', 'R9a'] }] });
expect(reason(s, 'A', { type: 'commit' })).toBe('받침대에서 타일을 1개 이상 내야 해요.');
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['R4a', 'R5a', 'R6a'] }, { tileIds: ['R7a', 'R8a', 'R9a'] }, { tileIds: ['K1a', 'K2a'] }] });
expect(reason(s, 'A', { type: 'commit' })).toBe('빨간 표시된 묶음을 고쳐 주세요.');
expect(rummikub.view(s, 'A').my!.check!.invalidIdx).toEqual([2]);
expect(rummikub.view(s, 'A').draft![2]).toMatchObject({ ok: false, problem: '3장 이상이어야 해요' });
test('joker retrieval needs the first meld: before it, the joker cannot be moved at all', () => {
const s = rig(mk(), { racks: { A: ['B6a', 'R10a', 'R11a', 'R12a'], B: ['B1a'] }, table: [['B5a', 'JK1', 'B7a']], melded: ['B'] });
expect(reason(s, 'A', { type: 'arrange', cells: lay(s, [['B5a', 'B6a', 'B7a'], ['R10a', 'R11a', 'R12a', 'JK1']]) })).toBe('첫 등록 전에는 바닥의 타일을 옮길 수 없어요.');
});
test('cheating attempts: foreign tiles, duplicates, table tiles into the rack, empty sets', () => {
test('rearranging without a rack tile is refused; leftover single tiles are refused (and highlighted)', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a', 'R7a', 'R8a', 'R9a']], melded: ['A'] });
s = arrange(s, 'A', [['R4a', 'R5a', 'R6a'], ['R7a', 'R8a', 'R9a']]);
expect(reason(s, 'A', { type: 'commit' })).toBe('받침대에서 타일을 1개 이상 내야 해요.');
s = arrange(s, 'A', [['R4a', 'R5a', 'R6a'], ['R7a', 'R8a', 'R9a'], ['K1a', 'K2a']]);
expect(reason(s, 'A', { type: 'commit' })).toBe('빨간 표시된 묶음을 고쳐 주세요.');
const v = rummikub.view(s, 'A');
const bad = v.my!.check!.invalidIdx;
expect(bad).toHaveLength(1);
expect(v.draft!.groups[bad[0]!]).toMatchObject({ ok: false, problem: '3장 이상이어야 해요', tileIds: ['K1a', 'K2a'] });
});
test('cheating attempts: foreign tiles, duplicates, two tiles on one cell, off the grid, table tiles into the rack', () => {
const s = rig(mk(), { racks: { A: ['K1a', 'K2a', 'K3a'], B: ['B1a', 'B2a', 'B3a'] }, table: [['R4a', 'R5a', 'R6a']], melded: ['A', 'B'] });
const base = tableSets(s);
expect(reason(s, 'A', { type: 'setDraft', sets: [...base, { tileIds: ['B1a', 'B2a', 'B3a'] }] })).toBe('내 받침대나 바닥에 없는 타일이에요.');
expect(reason(s, 'A', { type: 'setDraft', sets: [...base, { tileIds: ['O9a', 'O10a', 'O11a'] }] })).toBe('내 받침대나 바닥에 없는 타일이에요.');
expect(reason(s, 'A', { type: 'setDraft', sets: [...base, { tileIds: ['XX1', 'K2a', 'K3a'] }] })).toBe('내 받침대나 바닥에 없는 타일이에요.');
expect(reason(s, 'A', { type: 'setDraft', sets: [...base, { tileIds: ['K1a', 'K1a', 'K2a'] }] })).toBe('같은 타일이 두 번 들어 있어요.');
expect(reason(s, 'A', { type: 'setDraft', sets: [...base, { tileIds: ['K1a', 'K2a', 'K3a', 'R4a'] }] })).toBe('같은 타일이 두 번 들어 있어요.');
expect(reason(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['R4a', 'R5a'] }, { tileIds: ['K1a', 'K2a', 'K3a'] }] })).toBe('바닥의 타일은 내 받침대로 가져올 수 없어요.');
expect(rummikub.actionSchema.safeParse({ type: 'setDraft', sets: [{ tileIds: [] }] }).success).toBe(false);
expect(reason(s, 'B', { type: 'setDraft', sets: base })).toBe('지금은 내 차례가 아니에요.');
const with_ = (cells: Cell[]) => ({ type: 'arrange' as const, cells: [...s.draft.cells, ...cells] });
expect(reason(s, 'A', { type: 'arrange', cells: lay(s, [...base, ['B1a', 'B2a', 'B3a']]) })).toBe('내 받침대나 바닥에 없는 타일이에요.');
expect(reason(s, 'A', { type: 'arrange', cells: lay(s, [...base, ['O9a', 'O10a', 'O11a']]) })).toBe('내 받침대나 바닥에 없는 타일이에요.');
expect(reason(s, 'A', with_([{ id: 'XX1', r: 5, c: 0 }]))).toBe('내 받침대나 바닥에 없는 타일이에요.');
expect(reason(s, 'A', with_([{ id: 'K1a', r: 5, c: 0 }, { id: 'K1a', r: 5, c: 1 }]))).toBe('같은 타일이 두 번 들어 있어요.');
expect(reason(s, 'A', with_([{ id: 'K1a', r: 5, c: 0 }, { id: 'K2a', r: 5, c: 0 }]))).toBe('한 칸에 타일 두 개를 놓을 수 없어요.');
expect(reason(s, 'A', with_([{ id: 'K1a', r: BOARD_ROWS, c: 0 }]))).toBe('바닥 밖에는 놓을 수 없어요.');
expect(rummikub.actionSchema.safeParse(with_([{ id: 'K1a', r: 0, c: BOARD_COLS }])).success).toBe(false);
expect(rummikub.actionSchema.safeParse(with_([{ id: 'K1a', r: 0.5, c: 1 }])).success).toBe(false);
expect(reason(s, 'A', { type: 'arrange', cells: s.draft.cells.slice(1) })).toBe('바닥의 타일은 내 받침대로 가져올 수 없어요.');
// The same checks guard a commit that carries its own cells.
expect(reason(s, 'A', { type: 'commit', cells: lay(s, [...base, ['B1a', 'B2a', 'B3a']]) })).toBe('내 받침대나 바닥에 없는 타일이에요.');
expect(reason(s, 'B', { type: 'arrange', cells: s.draft.cells })).toBe('지금은 내 차례가 아니에요.');
expect(reason(s, 'Z', { type: 'draw' })).toBe('이 게임의 플레이어가 아니에요.');
// A valid commit puts exactly the played tiles on the table.
const t = play(s, 'A', [...base.map((d) => d.tileIds), ['K1a', 'K2a', 'K3a']]);
const t = play(s, 'A', [...base, ['K1a', 'K2a', 'K3a']]);
expect(t.racks.A).toEqual([]);
});
});
// ---------------------------------------------------------------- draft / undo
// ---------------------------------------------------------------- working table / commit
describe('초안과 되돌리기 (§5.6)', () => {
test('5 setDraft → 2 undo → the 3rd draft; reset → turn start; survives a save/reload', () => {
describe('놓아 보기와 완료 (§5.6)', () => {
test('arrange replaces the working table; resetDraft puts it back; it survives a save/reload', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a', 'K3a', 'K4a', 'K5a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a']], melded: ['A'] });
const base = tableSets(s);
const drafts = [1, 2, 3, 4, 5].map((k) => [...base, { tileIds: ['K1a', 'K2a', 'K3a', 'K4a', 'K5a'].slice(0, k) }]);
for (const d of drafts) s = act(s, 'A', { type: 'setDraft', sets: d });
s = act(s, 'A', { type: 'undoDraft' });
s = act(s, 'A', { type: 'undoDraft' });
expect(s.draft.sets).toEqual(drafts[2]!);
// Reconnect = the persisted state is reloaded; the draft is still there.
const start = s.draft.cells;
for (let k = 1; k <= 5; k++) s = arrange(s, 'A', [...tableSets(s), ['K1a', 'K2a', 'K3a', 'K4a', 'K5a'].slice(0, k)]);
expect(s.draft.edits).toBe(5);
expect(rummikub.view(s, 'A').my!.changed).toBe(true);
// Reconnect = the persisted state is reloaded; the working table is still there.
const reloaded = JSON.parse(JSON.stringify(s)) as RummikubState;
expect(rummikub.view(reloaded, 'A').draft!.map((d) => d.tileIds)).toEqual(drafts[2]!.map((d) => d.tileIds));
expect(rummikub.view(reloaded, 'A').draft!.cells).toEqual(s.draft.cells);
s = act(s, 'A', { type: 'resetDraft' });
expect(s.draft.sets.map((d) => d.tileIds)).toEqual(base.map((d) => d.tileIds));
expect(s.draft.cells).toEqual(start);
expect(rummikub.view(s, 'A').my!.changed).toBe(false);
// Reset can be undone too.
s = act(s, 'A', { type: 'undoDraft' });
expect(s.draft.sets).toEqual(drafts[2]!);
for (let i = 0; i < 3; i++) s = act(s, 'A', { type: 'undoDraft' });
expect(reason(s, 'A', { type: 'undoDraft' })).toBe('되돌릴 것이 없어요.');
// Moving a whole table set somewhere else is a change you can reset, but not a play.
s = act(s, 'A', { type: 'arrange', cells: placeTiles(s.draft.cells, ['R4a', 'R5a', 'R6a'], 6, 2)! });
expect(rummikub.view(s, 'A').my!.changed).toBe(true);
expect(reason(s, 'A', { type: 'commit' })).toBe('받침대에서 타일을 1개 이상 내야 해요.');
});
test('history keeps at most 100 steps', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a'], B: ['B1a'] }, melded: ['A'] });
for (let i = 0; i < 130; i++) s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: [i % 2 ? 'K1a' : 'K2a'] }] });
expect(s.draft.history).toHaveLength(100);
test('commit with cells: put down and checked in one step; the table keeps the grid places', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a', 'K3a', 'R1a'], B: ['B1a'] }, melded: ['A'] });
const cells = cellsOf([{ tileIds: ['K3a', 'K1a', 'K2a'], r: 4, c: 7 }]);
s = act(s, 'A', { type: 'commit', cells, turn: s.turnNo });
// Runs are written ascending in their strip.
expect(s.table).toEqual([{ id: 's1', tileIds: ['K1a', 'K2a', 'K3a'], kind: 'run', jokerAs: {}, r: 4, c: 7 }]);
expect(s.current).toBe('B');
// The next player's working table starts from the committed grid.
expect(s.draft.cells).toEqual(cellsOf(s.table));
});
test('draw with a changed draft throws the draft away and draws one', () => {
test('draw with a changed working table throws it away and draws one', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a', 'K3a'], B: ['B1a'] }, melded: ['A'] });
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['K1a', 'K2a', 'K3a'] }] });
s = arrange(s, 'A', [['K1a', 'K2a', 'K3a']]);
s = act(s, 'A', { type: 'draw' });
expect(s.table).toEqual([]);
expect(s.racks.A).toHaveLength(4);
@@ -332,7 +442,7 @@ describe('초안과 되돌리기 (§5.6)', () => {
test('invalidCommitPenalty=penalty3: an invalid commit reverts, draws 3 and ends the turn', () => {
let s = rig(mk({ invalidCommitPenalty: 'penalty3' }), { racks: { A: ['K1a', 'K2a'], B: ['B1a'] }, melded: ['A'] });
expect(reason(s, 'A', { type: 'commit' })).toBe('받침대에서 타일을 1개 이상 내야 해요.');
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['K1a', 'K2a'] }] });
s = arrange(s, 'A', [['K1a', 'K2a']]);
s = act(s, 'A', { type: 'commit' });
expect(s.table).toEqual([]);
expect(s.racks.A).toHaveLength(5);
@@ -364,49 +474,59 @@ describe('시간 초과 (§5.7, §8.5)', () => {
expect(rummikub.deadline!(s)).toBe(s.turnStartedAt + 60_000);
});
test('invalid draft: table and rack restored, 3 tiles drawn; with only 2 in the pool, 2', () => {
test('app rule (default): even a valid table goes back, the rack is restored and 1 tile is drawn', () => {
let s = pos();
const rackBefore = [...s.racks.A!];
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['R4a', 'R5a'] }, { tileIds: ['R6a', 'K1a'] }] });
const tableBefore = s.table;
s = arrange(s, 'A', [...tableSets(s), ['K1a', 'K2a', 'K3a']]);
expect(rummikub.view(s, 'A').my!.check!.ok).toBe(true);
s = act(s, 'A', { type: 'timeout' });
expect(s.table).toEqual(tableBefore);
expect(s.racks.A!.slice(0, 4)).toEqual(rackBefore);
expect(s.racks.A).toHaveLength(5);
expect(s.log.at(-1)).toMatchObject({ by: 'A', kind: 'timeoutDraw', count: 1 });
expect(s.current).toBe('B');
});
test('app rule (default): an unfinished table goes back and 1 tile is drawn', () => {
let s = pos();
s = arrange(s, 'A', [['R4a', 'R5a'], ['R6a', 'K1a']]);
s = act(s, 'A', { type: 'timeout' });
expect(setsOf(s)).toEqual([['R4a', 'R5a', 'R6a']]);
expect(s.racks.A!.slice(0, 4)).toEqual(rackBefore);
expect(s.racks.A).toHaveLength(7);
expect(s.lastDrawn.A).toHaveLength(3);
expect(s.current).toBe('B');
expect(s.racks.A).toHaveLength(5);
expect(s.lastDrawn.A).toHaveLength(1);
});
let t = pos({}, ['O13a', 'O13b']);
t = act(t, 'A', { type: 'setDraft', sets: [...tableSets(t), { tileIds: ['K1a'] }] });
test('rulebook options: valid table auto-committed; unfinished table → 3 tiles (only 2 in the pool → 2)', () => {
let c = pos({ timeoutValidDraft: 'commit' });
c = arrange(c, 'A', [...tableSets(c), ['K1a', 'K2a', 'K3a']]);
c = act(c, 'A', { type: 'timeout' });
expect(setsOf(c)).toEqual([['R4a', 'R5a', 'R6a'], ['K1a', 'K2a', 'K3a']]);
expect(c.racks.A).toEqual(['O9a']);
expect(c.log.at(-1)).toMatchObject({ kind: 'timeoutCommit', count: 3 });
let s = pos({ invalidTimeoutPenalty: 3 });
s = arrange(s, 'A', [['R4a', 'R5a'], ['R6a', 'K1a']]);
s = act(s, 'A', { type: 'timeout' });
expect(setsOf(s)).toEqual([['R4a', 'R5a', 'R6a']]);
expect(s.racks.A).toHaveLength(7);
expect(s.log.at(-1)).toMatchObject({ kind: 'penalty', count: 3 });
let t = pos({ invalidTimeoutPenalty: 3 }, ['O13a', 'O13b']);
t = arrange(t, 'A', [...tableSets(t), ['K1a']]);
t = act(t, 'A', { type: 'timeout' });
expect(t.racks.A).toHaveLength(6);
expect(t.pool).toEqual([]);
});
test('invalidTimeoutPenalty=1 draws only one', () => {
let s = pos({ invalidTimeoutPenalty: 1 });
s = act(s, 'A', { type: 'setDraft', sets: [...tableSets(s), { tileIds: ['K1a'] }] });
s = act(s, 'A', { type: 'timeout' });
expect(s.racks.A).toHaveLength(5);
});
test('valid draft: auto-commit (default) or revert + draw 1; no change: draw 1', () => {
let s = pos();
s = act(s, 'A', { type: 'setDraft', sets: [...tableSets(s), { tileIds: ['K1a', 'K2a', 'K3a'] }] });
s = act(s, 'A', { type: 'timeout' });
expect(setsOf(s)).toEqual([['R4a', 'R5a', 'R6a'], ['K1a', 'K2a', 'K3a']]);
expect(s.racks.A).toEqual(['O9a']);
expect(s.log.at(-1)).toMatchObject({ kind: 'timeoutCommit', count: 3 });
let r = pos({ timeoutValidDraft: 'revert' });
r = act(r, 'A', { type: 'setDraft', sets: [...tableSets(r), { tileIds: ['K1a', 'K2a', 'K3a'] }] });
r = act(r, 'A', { type: 'timeout' });
expect(setsOf(r)).toEqual([['R4a', 'R5a', 'R6a']]);
expect(r.racks.A).toHaveLength(5);
let u = pos();
test('nothing changed (or only moved around): draw 1, no penalty', () => {
let u = pos({ invalidTimeoutPenalty: 3 });
u = act(u, 'A', { type: 'arrange', cells: placeTiles(u.draft.cells, ['R4a', 'R5a', 'R6a'], 5, 5)! });
u = act(u, 'A', { type: 'timeout' });
expect(u.racks.A).toHaveLength(5);
expect(u.log.at(-1)).toMatchObject({ kind: 'timeoutDraw', count: 1 });
// The moved set went back to its place.
expect(u.table[0]).toMatchObject({ r: 0, c: 0 });
});
test('3 timeouts in a row → away: the deadline becomes short; acting again resets it', () => {
@@ -437,6 +557,11 @@ describe('시간 초과 (§5.7, §8.5)', () => {
s = act(s, s.current, { type: 'draw' });
expect(rummikub.deadline!(s)).toBeNull();
});
test('30-second turns', () => {
const s = mk({ turnSeconds: 30 });
expect(rummikub.deadline!(s)).toBe(s.turnStartedAt + 30_000);
});
});
// ---------------------------------------------------------------- scoring / end
@@ -562,29 +687,58 @@ describe('나가기', () => {
// ---------------------------------------------------------------- information
describe('정보 공개 (§8.3)', () => {
test('opponents and spectators see counts only; the draft is hidden unless showDraftToOthers', () => {
test('default (app): everybody sees the working table live — only the tiles put on it, never the rest of the rack', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a', 'K3a', 'O7a'], B: ['B1a', 'B9b'] }, table: [['R4a', 'R5a', 'R6a']], melded: ['A'] });
s = act(s, 'A', { type: 'setDraft', sets: [...tableSets(s), { tileIds: ['K1a', 'K2a', 'K3a'] }] });
s = act(s, 'A', { type: 'arrange', cells: [...s.draft.cells, { id: 'K1a', r: 2, c: 3 }] });
for (const viewer of ['B', null]) {
const v = rummikub.view(s, viewer);
expect(v.draft!.cells).toContainEqual({ id: 'K1a', r: 2, c: 3 });
expect(v.draft!.groups.find((g) => g.tileIds.includes('K1a'))).toMatchObject({ ok: false, r: 2, c: 3 });
expect(v.draftEdits).toBe(1);
expect(v.my?.check ?? null).toBeNull();
const json = JSON.stringify(v);
for (const id of ['K2a', 'K3a', 'O7a', ...s.pool, ...(viewer ? [] : s.racks.B!)]) expect(json.includes(`"${id}"`)).toBe(false);
expect(v.seats.find((x) => x.id === 'A')!.tiles).toBe(4);
}
// Put back on the rack → gone from everybody's view again.
s = act(s, 'A', { type: 'arrange', cells: cellsOf(s.table) });
expect(JSON.stringify(rummikub.view(s, 'B')).includes('"K1a"')).toBe(false);
expect(rummikub.secretsOf!(s, 'A')).toContain('K1a');
});
test('showDraftToOthers=false: opponents and spectators see counts and "thinking" only', () => {
let s = rig(mk({ showDraftToOthers: false }), { racks: { A: ['K1a', 'K2a', 'K3a', 'O7a'], B: ['B1a', 'B9b'] }, table: [['R4a', 'R5a', 'R6a']], melded: ['A'] });
s = arrange(s, 'A', [...tableSets(s), ['K1a', 'K2a', 'K3a']]);
for (const viewer of ['B', null]) {
const v = rummikub.view(s, viewer);
const json = JSON.stringify(v);
for (const id of [...s.racks.A!, ...s.pool, ...(viewer ? [] : s.racks.B!)]) expect(json.includes(`"${id}"`)).toBe(false);
expect(v.draft).toBeNull();
expect(v.draftEdits).toBe(1);
expect(v.seats.find((x) => x.id === 'A')!.tiles).toBe(4);
expect(v.poolCount).toBe(s.pool.length);
}
expect(rummikub.view(s, 'B').my!.rack).toEqual(['B1a', 'B9b']);
const own = rummikub.view(s, 'A');
expect(own.draft!.map((d) => d.ok)).toEqual([true, true]);
expect(own.draft!.groups.map((d) => d.ok)).toEqual([true, true]);
expect(own.my!.check).toMatchObject({ ok: true, fromRack: 3 });
expect(rummikub.secretsOf!(s, 'A')).toContain('K1a');
});
let t = rig(mk({ showDraftToOthers: true }), { racks: { A: ['K1a', 'K2a', 'K3a', 'O7a'], B: ['B1a'] }, melded: ['A'] });
t = act(t, 'A', { type: 'setDraft', sets: [{ tileIds: ['K1a', 'K2a', 'K3a'] }] });
const vb = rummikub.view(t, 'B');
expect(vb.draft!.map((d) => d.tileIds)).toEqual([['K1a', 'K2a', 'K3a']]);
expect(JSON.stringify(vb).includes('"O7a"')).toBe(false);
expect(rummikub.secretsOf!(t, 'A')).not.toContain('K1a');
test('drag preview (stream): public event, tiles still on the rack are hidden; nothing changes in the state', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a', 'K3a', 'O7a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a']], melded: ['A'] });
s = act(s, 'A', { type: 'arrange', cells: [...s.draft.cells, { id: 'K1a', r: 2, c: 0 }] });
expect(rummikub.isStreamAction!({ type: 'drag', ids: ['K1a'], x: 1, y: 1 })).toBe(true);
expect(rummikub.isStreamAction!({ type: 'arrange', cells: [] })).toBe(false);
const a: RummikubAction = { type: 'drag', ids: ['R4a', 'K1a', 'O7a', 'B1a'], x: 3.5, y: 2.25, turn: s.turnNo };
const out = actE(s, 'A', a);
expect(out.state).toBe(s);
expect(out.events).toEqual([{ type: 'drag', player: 'A', turn: s.turnNo, tiles: ['R4a', 'K1a', null], x: 3.5, y: 2.25 }]);
// Somebody else's / a late drag is dropped silently (no error toast), and nothing is sent with the option off.
expect(actE(s, 'B', a).events).toEqual([]);
expect(actE(s, 'A', { ...a, turn: s.turnNo - 1 }).events).toEqual([]);
const off = rig(mk({ showDraftToOthers: false }), { racks: { A: ['K1a'], B: ['B1a'] }, melded: ['A'] });
expect(actE(off, 'A', { type: 'drag', ids: ['K1a'], x: 0, y: 0 }).events).toEqual([]);
expect(rummikub.actionSchema.safeParse({ type: 'drag', ids: ['K1a'], x: 999, y: 0 }).success).toBe(false);
});
test('draw events carry no tile; only the drawer sees the new tile', () => {
@@ -612,38 +766,63 @@ describe('정보 공개 (§8.3)', () => {
describe('동시성', () => {
test('the same commit twice: the second is "not your turn"', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a', 'K3a', 'R1a'], B: ['B1a'] }, melded: ['A'] });
s = act(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['K1a', 'K2a', 'K3a'] }] });
s = arrange(s, 'A', [['K1a', 'K2a', 'K3a']]);
const commit = { type: 'commit' } as const;
s = act(s, 'A', commit);
expect(reason(s, 'A', commit)).toBe('지금은 내 차례가 아니에요.');
});
test('a setDraft from an earlier turn is refused (turn number)', () => {
test('an arrange from an earlier turn is refused (turn number)', () => {
let s = rig(mk(), { racks: { A: ['K1a', 'K2a', 'K3a', 'R1a'], B: ['B1a'] }, melded: ['A'] });
const turn = s.turnNo;
const cells = [{ id: 'K1a', r: 0, c: 0 }];
s = act(s, 'A', { type: 'draw' });
expect(reason(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['K1a'] }], turn })).toBe('지금은 내 차례가 아니에요.');
expect(reason(s, 'A', { type: 'arrange', cells, turn })).toBe('지금은 내 차례가 아니에요.');
s = act(s, 'B', { type: 'draw' });
expect(reason(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['K1a'] }], turn })).toBe('지난 차례의 요청이라 무시했어요.');
expect(rummikub.validate(s, 'A', { type: 'setDraft', sets: [{ tileIds: ['K1a'] }], turn: s.turnNo }).ok).toBe(true);
expect(reason(s, 'A', { type: 'arrange', cells, turn })).toBe('지난 차례의 요청이라 무시했어요.');
expect(rummikub.validate(s, 'A', { type: 'arrange', cells, turn: s.turnNo }).ok).toBe(true);
});
});
// ---------------------------------------------------------------- saves from before the grid
describe('예전 저장 (stateVersion 1)', () => {
test('a v1 game in progress gets grid places for the table and the working table, and plays on', () => {
const s = rig(mk(), { racks: { A: ['K1a', 'K2a', 'K3a', 'R1a'], B: ['B1a'] }, table: [['R4a', 'R5a', 'R6a'], ['B9a', 'K9a', 'O9a']], melded: ['A'] });
const old = JSON.parse(JSON.stringify(s)) as Record<string, any>;
old.table = old.table.map(({ r: _r, c: _c, ...t }: Record<string, unknown>) => t);
old.draft = { sets: [{ tileIds: ['R4a', 'R5a', 'R6a'], as: 'run' }, { tileIds: ['B9a', 'K9a', 'O9a'] }, { tileIds: ['K1a', 'K2a', 'K3a'] }], history: [[]], edits: 2 };
delete old.options.showDraftToOthers;
const m = rummikub.migrate!(old, 1);
expect(m.table.map((t) => [t.r, t.c])).toEqual([
[0, 0],
[0, 4],
]);
expect(stripsOf(m.draft.cells).map((x) => x.tileIds)).toEqual([['R4a', 'R5a', 'R6a'], ['B9a', 'K9a', 'O9a'], ['K1a', 'K2a', 'K3a']]);
expect(m.draft.edits).toBe(2);
expect(m.options.showDraftToOthers).toBe(true);
expect(rummikub.view(m, 'B').draft!.groups).toHaveLength(3);
const t = act(m, 'A', { type: 'commit' });
expect(t.racks.A).toEqual(['R1a']);
expect(rummikub.migrate!(t, 2)).toBe(t);
});
});
// ---------------------------------------------------------------- options / hints
describe('옵션과 힌트', () => {
test('every option has a Korean title; defaults follow the doc', () => {
test('every option has a Korean title; defaults follow the app', () => {
const shape = (rummikub.optionsSchema as unknown as { shape: Record<string, { meta(): { title?: string } | undefined }> }).shape;
for (const [k, v] of Object.entries(shape)) expect(v.meta()?.title, k).toBeTruthy();
expect(rummikub.defaultOptions).toEqual({
initialMeldPoints: 30,
turnSeconds: 60,
timeoutValidDraft: 'commit',
invalidTimeoutPenalty: 3,
timeoutValidDraft: 'revert',
invalidTimeoutPenalty: 1,
invalidCommitPenalty: 'reject',
jokerPenalty: 30,
initialMeldAllowExtend: false,
showDraftToOthers: false,
showDraftToOthers: true,
gamesPerMatch: '1',
hints: true,
});
@@ -661,9 +840,9 @@ describe('옵션과 힌트', () => {
const CONFIGS: Partial<RummikubOptions>[] = [
{},
{ initialMeldPoints: 0, showDraftToOthers: true },
{ initialMeldPoints: 0, showDraftToOthers: false },
{ initialMeldPoints: 50, invalidCommitPenalty: 'penalty3', jokerPenalty: 50 },
{ timeoutValidDraft: 'revert', invalidTimeoutPenalty: 1, initialMeldAllowExtend: true },
{ timeoutValidDraft: 'commit', invalidTimeoutPenalty: 3, initialMeldAllowExtend: true },
{ gamesPerMatch: '2', initialMeldPoints: 20 },
];
@@ -673,11 +852,13 @@ function conserved(st: unknown): void {
const s = st as RummikubState;
const all = [...s.pool, ...s.table.flatMap((t) => t.tileIds), ...Object.values(s.racks).flat()];
if (all.length !== 106 || new Set(all).size !== 106) throw new Error(`tiles not conserved: ${all.length}/${new Set(all).size}`);
// The committed table is always made of valid sets (checked once per turn; it only changes between turns).
// The committed table is always made of valid sets that are apart on the grid (checked once per turn).
const key = `${s.match.gameNo}:${s.turnNo}`;
if (checkedTable === key) return;
checkedTable = key;
for (const t of s.table) if (!normalizeSet({ tileIds: t.tileIds, as: t.kind })) throw new Error(`invalid table set ${t.tileIds}`);
const strips = stripsOf(cellsOf(s.table));
if (strips.length !== s.table.length) throw new Error('table sets touch on the grid');
}
describe('random playouts (docs/09 §7)', () => {