diff --git a/apps/server/src/rooms/rummikub.room.test.ts b/apps/server/src/rooms/rummikub.room.test.ts new file mode 100644 index 0000000..0e9f1e2 --- /dev/null +++ b/apps/server/src/rooms/rummikub.room.test.ts @@ -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; + +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 = { 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; + // 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 }]); + }); +}); diff --git a/apps/web/src/games/rummikub/help.test.ts b/apps/web/src/games/rummikub/help.test.ts index 9ac608c..b9da477 100644 --- a/apps/web/src/games/rummikub/help.test.ts +++ b/apps/web/src/games/rummikub/help.test.ts @@ -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 = {}, 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('게임이 끝났어요'); diff --git a/apps/web/src/games/rummikub/help.ts b/apps/web/src/games/rummikub/help.ts index 4d49868..ed189b5 100644 --- a/apps/web/src/games/rummikub/help.ts +++ b/apps/web/src/games/rummikub/help.ts @@ -54,7 +54,7 @@ export function helpNow(v: RummikubView, me: string | null, players: Record 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 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 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}를 누르면 확인 창이 뜨고, 바꾼 배치를 되돌린 뒤 차례를 끝내요.`, ); } diff --git a/apps/web/src/games/rummikub/index.tsx b/apps/web/src/games/rummikub/index.tsx index f5091dd..58b5779 100644 --- a/apps/web/src/games/rummikub/index.tsx +++ b/apps/web/src/games/rummikub/index.tsx @@ -1,9 +1,32 @@ -/** 루미큐브 화면 (docs/games/rummikub.md §9). Tap a tile to pick it up, then tap where it goes. */ +/** + * 루미큐브 화면 (docs/games/rummikub.md §9). Like the app: drag tiles from the rack onto a grid table and around it + * (tiles side by side form a set); tapping to select and tapping an empty cell works too. Everybody sees the + * working table live (arrange views + a drag preview stream). + */ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties } from 'react'; // Pure tile/set helpers only (no zod): keeps this lazy chunk small. -import { findMeld, normalizeSet, pickDisjoint, setProblem, sortTiles, tileLabel, tileOf, type DraftSet, type JokerAs, type TileColor } from '@bg/games/rummikub/rules'; -import type { LogEntry, RummikubOptions, RummikubView } from '@bg/games/rummikub'; -import type { PublicUser } from '@bg/shared/lite'; +import { + BOARD_COLS, + BOARD_ROWS, + cellsKey, + cellsOf, + findMeld, + freeSpot, + normalizeSet, + pickDisjoint, + placeTiles, + setProblem, + sortTiles, + stripsOf, + tileLabel, + tileOf, + type Cell, + type JokerAs, + type TileColor, +} from '@bg/games/rummikub/rules'; +import type { DragEvent, LogEntry, RummikubOptions, RummikubView } from '@bg/games/rummikub'; +import type { PublicUser, ServerMessage } from '@bg/shared/lite'; +import { socket } from '../../net/socket'; import { Avatar, ConfirmSheet } from '../../components/ui'; import { TurnTimer } from '../../components/TurnTimer'; import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback'; @@ -86,18 +109,37 @@ const CSS = ` .rk-player.gone { opacity: .55; } .rk-player .rk-count { font-weight: 800; font-variant-numeric: tabular-nums; } .rk-badge { display: inline-block; border-radius: 999px; padding: 0 8px; font-weight: 800; font-size: .75rem; line-height: 1.6; } -.rk-table { flex: 1; min-height: 200px; overflow: auto; background: var(--felt); border-radius: var(--radius-lg); padding: 10px; - display: flex; flex-wrap: wrap; align-content: flex-start; align-items: flex-start; gap: 10px 12px; box-shadow: inset 0 2px 10px rgba(0,0,0,.25); } -.rk-table-head { flex-basis: 100%; display: flex; justify-content: space-between; align-items: center; gap: 8px; color: #fff; font-weight: 700; font-size: .92rem; text-shadow: 0 1px 2px rgba(0,0,0,.4); } -.rk-empty { color: rgba(255,255,255,.85); font-size: .95rem; padding: 6px 2px; } -.rk-set { display: flex; flex-wrap: wrap; align-items: center; gap: 3px; padding: 4px; border-radius: 10px; border: 3px solid transparent; background: rgba(0,0,0,.18); max-width: 100%; } -.rk-set.ok { border-color: #86efac; } -.rk-set.bad { border-color: #fca5a5; border-style: dashed; background: rgba(127,29,29,.35); } -.rk-set.changed { animation: rk-flash 1s ease-out 2; } +.rk-table { flex: 1; min-height: 200px; min-width: 0; background: var(--felt); border-radius: var(--radius-lg); padding: 10px; + display: flex; flex-direction: column; gap: 8px; box-shadow: inset 0 2px 10px rgba(0,0,0,.25); } +.rk-table-head { display: flex; justify-content: space-between; align-items: center; gap: 8px; color: #fff; font-weight: 700; font-size: .92rem; text-shadow: 0 1px 2px rgba(0,0,0,.4); } +.rk-table-head > :first-child { flex: 1; min-width: 0; } +.rk-zoom { display: inline-flex; gap: 4px; } +.rk-zoom button { min-width: 36px; min-height: 32px; border-radius: 8px; border: 1px solid rgba(255,255,255,.55); background: rgba(255,255,255,.15); color: #fff; font-weight: 900; cursor: pointer; } +.rk-zoom button:disabled { opacity: .4; cursor: default; } +.rk-empty { position: absolute; left: 8px; top: 8px; margin: 0; color: rgba(255,255,255,.85); font-size: .95rem; pointer-events: none; } +/* The grid table: tiles are placed by cell (left/top), sets are tiles side by side in a row. */ +.rk-scroll { overflow: auto; max-width: 100%; flex: 1; min-height: 0; border-radius: 10px; overscroll-behavior: contain; } +.rk-board { position: relative; border-radius: 10px; } +.rk-board.grid { background-image: linear-gradient(to right, rgba(255,255,255,.09) 1px, transparent 1px), linear-gradient(to bottom, rgba(255,255,255,.09) 1px, transparent 1px); + background-size: var(--cw) var(--ch); box-shadow: inset 0 0 0 1px rgba(255,255,255,.12); } +.rk-board.aim { cursor: copy; } +.rk-board > .rk-tile { position: absolute; transition: left .2s ease, top .2s ease, transform .2s ease, box-shadow .2s ease, opacity .15s; z-index: 1; } +.rk-tile.grab { touch-action: none; cursor: grab; } +.rk-tile.lifted { opacity: .3; } +.rk-grp { position: absolute; border: 3px solid transparent; border-radius: 9px; pointer-events: none; } +.rk-grp.ok { border-color: #86efac; } +.rk-grp.bad { border-color: #fca5a5; border-style: dashed; background: rgba(127,29,29,.35); } +.rk-grp.changed { animation: rk-flash 1s ease-out 2; } @keyframes rk-flash { 0% { box-shadow: 0 0 0 5px #fde047; } 100% { box-shadow: 0 0 0 0 rgba(253,224,71,0); } } -.rk-problem { flex-basis: 100%; font-size: .8rem; font-weight: 700; color: #fff; background: #b91c1c; border-radius: 6px; padding: 1px 6px; } -.rk-setinfo { flex-basis: 100%; display: flex; gap: 6px; align-items: center; justify-content: space-between; font-size: .78rem; color: rgba(255,255,255,.9); } -.rk-setinfo button { background: rgba(255,255,255,.15); color: #fff; border: 1px solid rgba(255,255,255,.5); border-radius: 6px; min-height: 28px; padding: 0 6px; cursor: pointer; font-size: .78rem; } +.rk-problem { position: absolute; left: -3px; bottom: calc(100% + 1px); z-index: 2; white-space: nowrap; font-size: .72rem; font-weight: 700; color: #fff; + background: #b91c1c; border-radius: 6px; padding: 0 6px; line-height: 1.5; } +.rk-problem.below { bottom: auto; top: calc(100% + 1px); } +.rk-drop { position: absolute; z-index: 0; border: 2px dashed #fde047; border-radius: 8px; background: rgba(253,224,71,.2); pointer-events: none; } +.rk-ghostrow, .rk-dragrow { display: flex; pointer-events: none; } +.rk-ghostrow { position: absolute; z-index: 3; transition: left .2s linear, top .2s linear; filter: drop-shadow(0 6px 8px rgba(0,0,0,.35)); } +.rk-dragrow { position: fixed; z-index: 60; transform: rotate(-2deg) scale(1.06); filter: drop-shadow(0 10px 14px rgba(0,0,0,.4)); } +.rk-ghostrow .rk-tile, .rk-dragrow .rk-tile { margin: 0 2px; } +.rk-tile.rk-back { background: linear-gradient(#f4ead2, #e2d3ad); } .rk-tile { --w: 44px; --h: 60px; --tc: #111827; position: relative; width: var(--w); height: var(--h); flex: none; padding: 0; border-radius: 8px; background: linear-gradient(#fffdf7, #f1e7cf); border: 1px solid #c9b98f; box-shadow: 0 2px 0 #b5a172, 0 3px 6px rgba(0,0,0,.25); display: inline-flex; flex-direction: column; align-items: center; justify-content: center; color: var(--tc); font-weight: 900; line-height: 1; @@ -118,13 +160,9 @@ button.rk-tile:disabled { cursor: default; } .rk-tile.sm { --w: 38px; --h: 52px; } .rk-tile.xs { --w: 28px; --h: 38px; box-shadow: 0 1px 0 #b5a172; } .rk-tile:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } -.rk-slot { min-width: 30px; height: 52px; border: 2px dashed rgba(255,255,255,.85); border-radius: 8px; background: rgba(255,255,255,.14); color: #fff; - font-weight: 900; font-size: 1rem; cursor: pointer; padding: 0 4px; } -.rk-slot:hover, .rk-newset:hover { background: rgba(255,255,255,.28); } -.rk-newset { border: 2px dashed rgba(255,255,255,.9); color: #fff; background: rgba(255,255,255,.12); border-radius: 10px; min-height: 60px; padding: 0 16px; font-weight: 800; font-size: 1rem; cursor: pointer; } -.rk-meld { flex-basis: 100%; display: flex; align-items: center; gap: 8px; color: #fff; font-weight: 700; font-size: .9rem; } +.rk-meld { display: flex; align-items: center; gap: 8px; color: #fff; font-weight: 700; font-size: .9rem; } .rk-meld progress { flex: 1; height: 12px; accent-color: #facc15; } -.rk-bar { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 6px; } +.rk-bar { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 6px; } .rk-bar .btn { min-height: 52px; padding: 0 6px; font-size: .98rem; } .rk-msg { margin: 0; min-height: 1.4em; text-align: center; font-size: .92rem; } .rk-rackwrap { display: flex; flex-direction: column; gap: 6px; } @@ -132,24 +170,25 @@ button.rk-tile:disabled { cursor: default; } .rk-rackhead .segmented button { min-height: 40px; } .rk-rack { background: var(--wood); border-radius: var(--radius-lg); padding: 10px 8px 14px; display: flex; flex-wrap: wrap; gap: 5px; min-height: 84px; box-shadow: inset 0 -7px 0 var(--wood-line); align-content: flex-start; } +.rk-rack.drop { outline: 3px dashed var(--focus); outline-offset: 2px; } .rk-rack-empty { color: #3b2a0a; font-weight: 700; align-self: center; } .rk-result { display: grid; gap: 6px; } .rk-result-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } .rk-mini { display: inline-flex; gap: 2px; flex-wrap: wrap; } @media (max-width: 1099px) { - .rk-table { overflow: visible; min-height: 160px; } + .rk-table { min-height: 160px; } } @media (max-width: 719px) { .rk-bar { position: sticky; bottom: 0; z-index: 5; background: var(--bg); padding: 6px 0; grid-template-columns: repeat(3, minmax(0, 1fr)); } .rk-bar .btn { min-height: 48px; font-size: .95rem; } .rk-tile.sm { --w: 34px; --h: 47px; } - .rk-slot { height: 47px; min-width: 28px; } - .rk-table { padding: 8px; gap: 8px; } + .rk-table { padding: 8px; gap: 6px; } .rk-player { font-size: .85rem; padding: 3px 8px 3px 4px; } } @media (prefers-reduced-motion: reduce) { .rk-tile { transition: none; } - .rk-set.changed { animation: none; box-shadow: 0 0 0 3px #fde047; } + .rk-board > .rk-tile, .rk-ghostrow { transition: none; } + .rk-grp.changed { animation: none; box-shadow: 0 0 0 3px #fde047; } } `; @@ -178,13 +217,16 @@ interface TileProps { fresh?: boolean; /** Extra animation class (anim-deal / anim-pop) and its CSS variables. */ anim?: string; + className?: string; style?: CSSProperties; onClick?: () => void; + /** Start of a drag (my tiles in my turn). */ + onPointerDown?: (e: React.PointerEvent) => void; } -function Tile({ id, size = 'md', as, selected, hint, fresh, anim, style, onClick }: TileProps) { +function Tile({ id, size = 'md', as, selected, hint, fresh, anim, className, style, onClick, onPointerDown }: TileProps) { const t = tileOf(id); - const cls = `rk-tile${size !== 'md' ? ` ${size}` : ''}${hint ? ' hint' : ''}${fresh ? ' fresh' : ''}${anim ? ` ${anim}` : ''}`; + const cls = `rk-tile${size !== 'md' ? ` ${size}` : ''}${hint ? ' hint' : ''}${fresh ? ' fresh' : ''}${anim ? ` ${anim}` : ''}${className ? ` ${className}` : ''}`; const body = t.kind === 'joker' ? ( <> @@ -209,85 +251,163 @@ function Tile({ id, size = 'md', as, selected, hint, fresh, anim, style, onClick ); } return ( - ); } -// ---------------------------------------------------------------- draft editing - -/** Keeps a set in a readable order: the server's interpretation when valid, otherwise as placed. */ -function arrange(d: DraftSet): DraftSet { - const n = normalizeSet(d); - const tileIds = n ? n.tileIds : d.tileIds; - return d.as ? { tileIds, as: d.as } : { tileIds }; -} - -type Target = { set: number; at: 'start' | 'end' } | 'new' | 'rack'; - -/** Moves `sel` to the target; tiles that were on the table at turn start never go back to the rack. */ -function moveTiles(sets: DraftSet[], sel: string[], target: Target, onTable0: Set): DraftSet[] | null { - const moving = target === 'rack' ? sel.filter((id) => !onTable0.has(id)) : sel; - if (!moving.length) return null; - const ordered = sortTiles(moving, 'number'); - const next: DraftSet[] = sets.map((d) => ({ ...d, tileIds: d.tileIds.filter((id) => !moving.includes(id)) })); - let touched: DraftSet | null = null; - if (target === 'new') { - touched = { tileIds: ordered }; - next.push(touched); - } else if (target !== 'rack') { - touched = next[target.set]!; - touched.tileIds = target.at === 'start' ? [...ordered, ...touched.tileIds] : [...touched.tileIds, ...ordered]; - } - return next.filter((d) => d.tileIds.length > 0).map((d) => (d === touched ? arrange(d) : d)); -} - // ---------------------------------------------------------------- board +/** Rows shown at least (more appear below the lowest tile, up to BOARD_ROWS). */ +const MIN_ROWS = 6; +const ZOOMS = [1, 1.5, 2, 2.5]; +/** Live drag preview to the others: at most this often (the socket allows 20 messages a second). */ +const DRAG_SEND_MS = 200; +/** Pointer travel before a press becomes a drag (a shorter press is a tap: select). */ +const DRAG_START_PX = 6; +let dragCs = Date.now() * 1000 + 700_000; + +interface Group { + tileIds: string[]; + r: number; + c: number; + ok: boolean; + problem: string | null; + jokerAs: Record; + points: number; + /** Same tiles at the same place as a committed set (its id), else null. */ + tableId: string | null; +} + +/** A press on one of my tiles; becomes a drag after DRAG_START_PX. */ +interface Press { + id: string; + pid: number; + x0: number; + y0: number; + /** Pointer offset inside the pressed tile. */ + offX: number; + offY: number; + started: boolean; + ids: string[]; + grab: number; + lastSend: number; + sent: boolean; + /** Trailing preview: the last position is always sent, at most DRAG_SEND_MS after the previous one. */ + trail: ReturnType | null; +} + +/** Where the dragged row would land. */ +type DropTarget = { kind: 'board'; r: number; c: number } | { kind: 'rack' } | null; + +/** Somebody else's tiles in hand (drag preview stream). */ +interface Ghost { + player: string; + turn: number; + tiles: (string | null)[]; + x: number; + y: number; +} + +/** Moves an element that already sits at its new place so it slides from `from` (no CSS left/top transition meanwhile). */ +function slideFrom(el: Element | null, from: DOMRect | null): void { + if (!(el instanceof HTMLElement) || !from) return; + el.style.transition = 'none'; + flyFrom(el, from, { ms: 220, scale: 1, rotate: 0 }); + requestAnimationFrame(() => requestAnimationFrame(() => (el.style.transition = ''))); +} + +const tileEl = (scope: string, id: string) => document.querySelector(`${scope} [data-tile="${cssEsc(id)}"]`); + function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardProps) { const my = v.my; const mine = v.phase === 'playing' && !!me && v.current === me; const [sel, setSel] = useState([]); const [hintIds, setHintIds] = useState([]); - const [local, setLocal] = useState(null); + const [local, setLocal] = useState(null); const [sortBy, setSortBy] = useState<'color' | 'number'>(() => (localStorage.getItem('rk-sort') === 'number' ? 'number' : 'color')); + const [zoom, setZoom] = useState(() => { + const z = Number(localStorage.getItem('rk-zoom')); + return ZOOMS.includes(z) ? z : null; + }); + const [boxW, setBoxW] = useState(0); const [msg, setMsg] = useState(''); const [confirm, setConfirm] = useState(null); const [announce, setAnnounce] = useState(''); + /** My tiles in hand: pointer position + where they would land. */ + const [hand, setHand] = useState<{ ids: string[]; grab: number; x: number; y: number; offX: number; offY: number; target: DropTarget } | null>(null); + const [ghost, setGhost] = useState(null); const wasMine = useRef(false); const lastLog = useRef(''); // Animations: tiles dealt onto my rack, a shaking area, a big banner (tile flights use card-fx, see below). const [fly, setFly] = useTimed<{ ids: string[]; gap: number }>(); const [shake, setShake] = useTimed(); const [banner, showBanner] = useBanner(); - /** Where the tiles I just moved were (captured on the tap), so they fly from there to their new place. */ + /** Where the tiles I just moved were on screen, so they slide from there to their new place. */ const movedFrom = useRef | null>(null); /** Who had the turn on the previous render: tiles that newly show up on the table come from that seat. */ const prevCurrent = useRef(v.current); const winTimer = useRef | undefined>(undefined); useEffect(() => () => clearTimeout(winTimer.current), []); const snap = useRef<{ log: string; gameNo: number; phase: string; turnNo: number; edits: number; melded: Record; table: Set } | null>(null); + const boxRef = useRef(null); + const boardRef = useRef(null); + const rackRef = useRef(null); + const press = useRef(null); + const handRef = useRef(null); + const lastTap = useRef<{ id: string; at: number } | null>(null); + const suppressClick = useRef(false); - const serverSets: DraftSet[] = useMemo( - () => (v.draft ? v.draft.map((d) => (d.as ? { tileIds: d.tileIds, as: d.as } : { tileIds: d.tileIds })) : v.table.map((t) => ({ tileIds: t.tileIds, as: t.kind }))), - [v.draft, v.table], - ); - // Optimistic draft until the server answers (cleared when nothing is pending any more). + const serverCells: Cell[] = useMemo(() => (v.draft ? v.draft.cells : cellsOf(v.table)), [v.draft, v.table]); + // Optimistic working table until the server answers (cleared when nothing is pending any more). useEffect(() => { if (!pending) setLocal(null); }, [pending, v.turnNo, v.draftEdits]); - const sets = mine && local ? local : serverSets; + const cells = mine && local ? local : serverCells; const onTable0 = useMemo(() => new Set(v.table.flatMap((t) => t.tileIds)), [v.table]); - const inSets = useMemo(() => new Set(sets.flatMap((d) => d.tileIds)), [sets]); - const rack = useMemo(() => sortTiles((my?.rack ?? []).filter((id) => !inSets.has(id)), sortBy), [my?.rack, inSets, sortBy]); + const onBoard = useMemo(() => new Set(cells.map((x) => x.id)), [cells]); + const rack = useMemo(() => sortTiles((my?.rack ?? []).filter((id) => !onBoard.has(id)), sortBy), [my?.rack, onBoard, sortBy]); const fresh = new Set(my?.lastDrawn ?? []); + const locked = !my?.melded && !v.options.initialMeldAllowExtend; + const groups: Group[] = useMemo( + () => + stripsOf(cells).map((x) => { + const n = normalizeSet({ tileIds: x.tileIds }); + const t = v.table.find((t) => t.r === x.r && t.c === x.c && t.tileIds.length === x.tileIds.length && t.tileIds.every((id) => x.tileIds.includes(id))); + return { ...x, ok: !!n, problem: n ? null : setProblem({ tileIds: x.tileIds }), jokerAs: n?.jokerAs ?? {}, points: n?.points ?? 0, tableId: t?.id ?? null }; + }), + [cells, v.table], + ); + const jokerAs = useMemo(() => Object.assign({}, ...groups.map((g) => g.jokerAs)) as Record, [groups]); + // First-meld progress from what is on the board right now (new sets made of rack tiles only). + const meldNow = groups.filter((g) => g.ok && g.tileIds.every((id) => !onTable0.has(id))).reduce((a, g) => a + g.points, 0); + + // Grid size: fit the width, zoom in on small screens (the board scrolls). + useLayoutEffect(() => { + const el = boxRef.current; + if (!el) return; + setBoxW(el.clientWidth); + if (typeof ResizeObserver === 'undefined') return; + const ro = new ResizeObserver(() => setBoxW(el.clientWidth)); + ro.observe(el); + return () => ro.disconnect(); + }, []); + const fit = boxW ? Math.floor((boxW - 2) / BOARD_COLS) : 36; + const z = zoom ?? (fit >= 30 ? 1 : fit >= 21 ? 1.5 : 2); + const cw = Math.max(16, Math.min(64, Math.round(fit * z))); + const ch = Math.round(cw * 1.36); + const lowest = cells.reduce((m, x) => Math.max(m, x.r), -1); + const rows = Math.min(BOARD_ROWS, Math.max(MIN_ROWS, lowest + 2 + (hand ? 1 : 0))); + const tileVars = { '--w': `${cw - 4}px`, '--h': `${ch - 4}px` } as CSSProperties; // Turn change: clear selection and hints, announce. useEffect(() => { setSel([]); setHintIds([]); setMsg(''); + setHand(null); + press.current = null; if (mine && !wasMine.current) { haptic(40); sounds.myTurn(); @@ -341,6 +461,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr } else if (e.kind === 'draw' || e.kind === 'timeoutDraw') { snd.draw(); drawFx(e.by, mineMove ? (v.my?.lastDrawn ?? []) : [], e.count || 1, 90); + if (e.kind === 'timeoutDraw' && mineMove) showBanner('시간 초과', 'dark', `바닥을 되돌리고 ${e.count}장 가져왔어요`); } else if (e.kind === 'penalty') { sfx.bad(); for (let i = 0; i < Math.min(e.count, 3); i++) snd.draw(250 + i * 160); @@ -380,27 +501,82 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr /** Tiles drawn from the pool: mine fly out of it onto my rack, anyone else's as face-down tiles to their seat. */ const drawFx = (by: string, mineIds: string[], n: number, gap: number) => { const pool = fxEl('rk-pool'); - if (by === me) mineIds.forEach((id, i) => flyFrom(document.querySelector(`.rk-rack [data-tile="${cssEsc(id)}"]`), pool, { delay: i * gap, rotate: 8 })); + if (by === me) mineIds.forEach((id, i) => flyFrom(tileEl('.rk-rack', id), pool, { delay: i * gap, rotate: 8 })); else flyGhost(pool, seatEl(by), { className: 'rk-ghost', count: Math.min(n, 6), gap }); }; - // Tiles I moved (rack ↔ table, between sets) slide from where I tapped them. + // ---- somebody else's tiles in hand (drag preview stream, docs §9 "모두에게 보이기") + const meRef = useRef(me); + meRef.current = me; + const ghostRef = useRef<{ g: Ghost; rects: DOMRect[] } | null>(null); + useEffect(() => { + let clear: ReturnType | undefined; + const off = socket.subscribe((m: ServerMessage) => { + if (m.t !== 'stream') return; + for (const ev of m.events as Partial[]) { + if (ev.type !== 'drag' || !ev.player || ev.player === meRef.current || !ev.tiles) continue; + setGhost(ev.tiles.length ? (ev as Ghost) : null); + clearTimeout(clear); + // A drag that never ends (connection lost) fades away. + clear = setTimeout(() => setGhost(null), 2500); + } + }); + return () => { + off(); + clearTimeout(clear); + }; + }, []); + // Remember where the ghost tiles are on screen: the dropped tiles slide from there. + useLayoutEffect(() => { + if (!ghost) return; + const els = document.querySelectorAll('.rk-ghostrow > *'); + ghostRef.current = { g: ghost, rects: [...els].map((el) => el.getBoundingClientRect()) }; + }); + useEffect(() => { + setGhost(null); + }, [v.draftEdits, v.turnNo, v.phase]); + + // ---- tile movements + // Board tiles slide (CSS left/top). Tiles I dropped or tapped come from where they were; the other player's + // dropped tiles come from their ghost in hand, or (new on the table, no preview) from their seat. useLayoutEffect(() => { const from = movedFrom.current; if (!from) return; movedFrom.current = null; - [...from].forEach(([id, r], i) => flyFrom(document.querySelector(`.rk-root [data-tile="${cssEsc(id)}"]`), r, { ms: 300, delay: i * 35, scale: 0.9, rotate: 0 })); + [...from].forEach(([id, r]) => slideFrom(tileEl('.rk-root', id), r)); }); - // Tiles that newly show up on the table in somebody else's turn (their live draft or their commit) fly from their seat. - const tableIds = useMemo(() => (mine ? [] : sets.flatMap((d) => d.tileIds)), [mine, sets]); + const boardKey = useMemo(() => cellsKey(cells), [cells]); + const prevCells = useRef | null>(null); + useLayoutEffect(() => { + const now = new Map(cells.map((x) => [x.id, `${x.r}.${x.c}`])); + const before = prevCells.current; + prevCells.current = now; + const gh = ghostRef.current; + ghostRef.current = null; + if (!before || mine || !gh) return; + // The other player's drop: tiles from the ghost row (in order) slide from their place in hand. + let k = 0; + gh.g.tiles.forEach((id, i) => { + const rect = gh.rects[i] ?? null; + if (id && before.get(id) !== now.get(id)) slideFrom(tileEl('.rk-board', id), rect); + else if (!id) { + // A hidden tile from their rack: the k-th tile that is new on the board. + const fresh = cells.filter((x) => !before.has(x.id)); + const t = fresh[k++]; + if (t) slideFrom(tileEl('.rk-board', t.id), rect); + } + }); + }, [boardKey]); // eslint-disable-line react-hooks/exhaustive-deps + // Tiles that newly show up on the table in somebody else's turn without a preview (commit, computer) fly from their seat. + const tableIds = useMemo(() => (mine ? [] : cells.map((x) => x.id)), [mine, cells]); useNewEntries( tableIds, (id) => id, (fresh) => { const by = prevCurrent.current; - if (!by || by === me) return; + if (!by || by === me || ghost) return; const seat = seatEl(by); - fresh.forEach((id, i) => flyFrom(document.querySelector(`.rk-table [data-tile="${cssEsc(id)}"]`), seat, { delay: i * 60, rotate: -8 })); + fresh.forEach((id, i) => flyFrom(tileEl('.rk-board', id), seat, { delay: i * 60, rotate: -8 })); }, 20, ); @@ -408,51 +584,233 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr prevCurrent.current = v.current; }); - // Drop selected tiles that disappeared (e.g. after undo on the server). + // Drop selected tiles that disappeared (e.g. after a reset on the server). useEffect(() => { - setSel((s) => (s.every((id) => inSets.has(id) || rack.includes(id)) ? s : s.filter((id) => inSets.has(id) || rack.includes(id)))); - }, [inSets, rack]); + setSel((s) => (s.every((id) => onBoard.has(id) || rack.includes(id)) ? s : s.filter((id) => onBoard.has(id) || rack.includes(id)))); + }, [onBoard, rack]); - const send = (next: DraftSet[]) => { + // ---- placing tiles + + const rectsOf = (ids: readonly string[]) => { + const rects = new Map(); + for (const id of ids) { + const el = tileEl('.rk-root', id); + if (el) rects.set(id, el.getBoundingClientRect()); + } + return rects; + }; + + const send = (next: Cell[], from: Map) => { + movedFrom.current = from; + snd.place(); + setSel([]); + setHintIds([]); setLocal(next); - act({ type: 'setDraft', sets: next, turn: v.turnNo }); + act({ type: 'arrange', cells: next, turn: v.turnNo }); + }; + + /** Order of tiles moved together: as they lie on the board, else by number (rack tiles). */ + const ordered = (ids: readonly string[]): string[] => { + const at = new Map(cells.map((x) => [x.id, x.r * BOARD_COLS + x.c])); + return ids.every((id) => at.has(id)) ? [...ids].sort((a, b) => at.get(a)! - at.get(b)!) : sortTiles(ids, 'number'); + }; + + /** Puts `ids` with the first one on (r, c); null + message when it is not allowed. */ + const placeAt = (ids: string[], r: number, c: number): Cell[] | null => { + if (locked && ids.some((id) => onTable0.has(id))) { + setMsg('첫 등록 전에는 바닥의 타일을 옮길 수 없어요. 내 받침대 타일만 놓아 주세요.'); + return null; + } + const next = placeTiles(cells, ids, r, c); + if (!next) { + setMsg('그 줄에는 자리가 모자라요. 다른 줄에 놓아 주세요.'); + return null; + } + if (locked) { + const before = new Map(cells.map((x) => [x.id, `${x.r}.${x.c}`])); + if (next.some((x) => onTable0.has(x.id) && before.get(x.id) !== `${x.r}.${x.c}`)) { + setMsg('첫 등록 전에는 바닥 묶음을 밀 수 없어요. 빈 곳에 놓아 주세요.'); + return null; + } + } + setMsg(''); + return next; + }; + + const toRack = (ids: string[]) => { + const back = ids.filter((id) => onBoard.has(id) && !onTable0.has(id)); + if (ids.some((id) => onTable0.has(id))) setMsg('바닥에 있던 타일은 받침대로 가져올 수 없어요.'); + else setMsg(''); + if (!back.length) return; + send( + cells.filter((x) => !back.includes(x.id)), + rectsOf(back), + ); + }; + + const newSet = () => { + const ids = ordered(sel); + if (!ids.length) return; + const spot = freeSpot( + cells.filter((x) => !ids.includes(x.id)), + ids.length, + ); + if (!spot) return setMsg('바닥에 빈 곳이 없어요.'); + const next = placeAt(ids, spot.r, spot.c); + if (next) send(next, rectsOf(ids)); }; const toggle = (id: string) => { if (!mine) return; + if (suppressClick.current) return; setHintIds([]); setMsg(''); snd.pick(); + // Double tap on a board tile picks up its whole set. + const now = performance.now(); + const prevTap = lastTap.current; + lastTap.current = { id, at: now }; + const g = groups.find((x) => x.tileIds.includes(id)); + if (g && prevTap && prevTap.id === id && now - prevTap.at < 400) { + lastTap.current = null; + setSel((s) => [...new Set([...s, ...g.tileIds])]); + return; + } setSel((s) => (s.includes(id) ? s.filter((x) => x !== id) : [...s, id])); }; - const move = (target: Target) => { - if (!mine || !sel.length) return; - if (!my?.melded && !v.options.initialMeldAllowExtend && sel.some((id) => onTable0.has(id))) { - setMsg('첫 등록 전에는 바닥의 타일을 옮길 수 없어요. 내 받침대 타일만 골라 주세요.'); - return; - } - if (target === 'rack' && sel.some((id) => onTable0.has(id))) setMsg('바닥에 있던 타일은 받침대로 가져올 수 없어요.'); - else setMsg(''); - const next = moveTiles(sets, sel, target, onTable0); - if (!next) return; - const rects = new Map(); - for (const id of sel) { - const el = document.querySelector(`.rk-root [data-tile="${cssEsc(id)}"]`); - if (el) rects.set(id, el.getBoundingClientRect()); - } - movedFrom.current = rects; - snd.place(); - setSel([]); - send(next); + /** Tap on an empty cell with tiles selected: they go there. */ + const tapBoard = (e: React.MouseEvent) => { + if (!mine || !sel.length || (e.target as Element).closest('.rk-tile')) return; + const b = boardRef.current!.getBoundingClientRect(); + const r = Math.floor((e.clientY - b.top) / ch); + const c = Math.floor((e.clientX - b.left) / cw); + const ids = ordered(sel); + const next = placeAt(ids, r, c); + if (next) send(next, rectsOf(ids)); }; - const toggleKind = (i: number) => { - const d = sets[i]!; - const cur = v.draft?.[i]?.kind ?? 'run'; - send(sets.map((x, k) => (k === i ? { tileIds: d.tileIds, as: cur === 'run' ? 'group' : 'run' } : x))); + // ---- drag and drop (mouse and touch: pointer events on window, so the tile may leave its box) + const latest = useRef({ mine, sel, cells, cw, ch, rows, turnNo: v.turnNo, share: v.options.showDraftToOthers, ordered, placeAt, toRack, send, locked, onTable0 }); + latest.current = { mine, sel, cells, cw, ch, rows, turnNo: v.turnNo, share: v.options.showDraftToOthers, ordered, placeAt, toRack, send, locked, onTable0 }; + + const startPress = (e: React.PointerEvent, id: string) => { + if (!mine || (e.pointerType === 'mouse' && e.button !== 0)) return; + const r = e.currentTarget.getBoundingClientRect(); + press.current = { id, pid: e.pointerId, x0: e.clientX, y0: e.clientY, offX: e.clientX - r.left, offY: e.clientY - r.top, started: false, ids: [], grab: 0, lastSend: 0, sent: false, trail: null }; }; + useEffect(() => { + const targetAt = (x: number, y: number, p: Press): DropTarget => { + const L = latest.current; + const box = boxRef.current?.getBoundingClientRect(); + const board = boardRef.current?.getBoundingClientRect(); + if (box && board && x >= box.left && x <= box.right && y >= box.top && y <= box.bottom) { + const left = x - p.offX - p.grab * L.cw; + const top = y - p.offY; + const r = Math.round((top - board.top) / L.ch); + const c = Math.round((left - board.left) / L.cw); + if (r >= 0 && r < BOARD_ROWS) return { kind: 'board', r: Math.min(r, L.rows - 1), c: Math.max(0, Math.min(c, BOARD_COLS - p.ids.length)) }; + return null; + } + const rk = rackRef.current?.getBoundingClientRect(); + if (rk && x >= rk.left && x <= rk.right && y >= rk.top - 20 && y <= rk.bottom) return { kind: 'rack' }; + return null; + }; + const stream = (p: Press, x: number, y: number) => { + const L = latest.current; + if (!L.share) return; + const now = performance.now(); + if (now - p.lastSend < DRAG_SEND_MS) { + if (p.trail) clearTimeout(p.trail); + p.trail = setTimeout( + () => { + p.trail = null; + if (press.current === p) stream(p, x, y); + }, + DRAG_SEND_MS - (now - p.lastSend), + ); + return; + } + p.lastSend = now; + p.sent = true; + const board = boardRef.current?.getBoundingClientRect(); + if (!board) return; + const gx = (x - p.offX - p.grab * L.cw - board.left) / L.cw; + const gy = (y - p.offY - board.top) / L.ch; + const clamp = (n: number, lo: number, hi: number) => Math.round(Math.max(lo, Math.min(hi, n)) * 100) / 100; + socket.send({ t: 'act', cs: ++dragCs, a: { type: 'drag', ids: p.ids, x: clamp(gx, -4, BOARD_COLS + 4), y: clamp(gy, -4, BOARD_ROWS + 6), turn: L.turnNo } }); + }; + const move = (e: PointerEvent) => { + const p = press.current; + if (!p || e.pointerId !== p.pid) return; + const L = latest.current; + if (!L.mine) { + press.current = null; + setHand(null); + return; + } + if (!p.started) { + if (Math.hypot(e.clientX - p.x0, e.clientY - p.y0) < DRAG_START_PX) return; + const ids = L.ordered(L.sel.includes(p.id) ? L.sel : [p.id]); + if (L.locked && ids.some((id) => L.onTable0.has(id))) { + press.current = null; + setMsg('첫 등록 전에는 바닥의 타일을 옮길 수 없어요. 내 받침대 타일만 놓아 주세요.'); + return; + } + p.started = true; + p.ids = ids; + p.grab = ids.indexOf(p.id); + snd.pick(); + } + e.preventDefault(); + // The tiles in hand follow the pointer without a re-render; the board re-renders only when the target cell changes. + const row = handRef.current; + if (row) { + row.style.left = `${e.clientX - p.offX - p.grab * L.cw}px`; + row.style.top = `${e.clientY - p.offY}px`; + } + const target = targetAt(e.clientX, e.clientY, p); + setHand((h) => + h && h.ids === p.ids && JSON.stringify(h.target) === JSON.stringify(target) ? h : { ids: p.ids, grab: p.grab, x: e.clientX, y: e.clientY, offX: p.offX, offY: p.offY, target }, + ); + stream(p, e.clientX, e.clientY); + }; + const up = (e: PointerEvent) => { + const p = press.current; + if (!p || e.pointerId !== p.pid) return; + press.current = null; + if (p.trail) clearTimeout(p.trail); + if (!p.started) return; // a tap: the click handler selects + suppressClick.current = true; + setTimeout(() => (suppressClick.current = false), 0); + setHand(null); + const L = latest.current; + const t = e.type === 'pointerup' ? targetAt(e.clientX, e.clientY, p) : null; + // Where the tiles in hand are on screen (they slide from there into place). + const from = new Map(); + p.ids.forEach((id, i) => from.set(id, new DOMRect(e.clientX - p.offX + (i - p.grab) * L.cw, e.clientY - p.offY, L.cw - 4, L.ch - 4))); + if (t?.kind === 'board') { + const next = L.placeAt(p.ids, t.r, t.c); + if (next && cellsKey(next) !== cellsKey(L.cells)) return L.send(next, from); + } else if (t?.kind === 'rack') { + if (p.ids.some((id) => L.cells.some((x) => x.id === id))) return L.toRack(p.ids); + } + // Nothing happened: tell the others the tiles went back. + if (p.sent) socket.send({ t: 'act', cs: ++dragCs, a: { type: 'drag', ids: [], x: 0, y: 0, turn: L.turnNo } }); + }; + window.addEventListener('pointermove', move, { passive: false }); + window.addEventListener('pointerup', up); + window.addEventListener('pointercancel', up); + return () => { + window.removeEventListener('pointermove', move); + window.removeEventListener('pointerup', up); + window.removeEventListener('pointercancel', up); + }; + }, []); + + // ---- buttons + const hint = () => { const free = rack; let found: string[][] = []; @@ -466,37 +824,53 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr snd.pick(); setHintIds(found.flat()); setSel(found[0]!); - setMsg(found.length > 1 ? `보라색 타일로 묶음 ${found.length}개를 만들 수 있어요. 첫 묶음을 골라 두었어요. "새 묶음"을 눌러 보세요.` : '보라색 타일로 묶음을 만들 수 있어요. 골라 두었으니 "새 묶음"을 눌러 보세요.'); + setMsg( + found.length > 1 + ? `보라색 타일로 묶음 ${found.length}개를 만들 수 있어요. 첫 묶음을 골라 두었어요. 바닥으로 끌어다 놓거나 [새 묶음]을 눌러 보세요.` + : '보라색 타일로 묶음을 만들 수 있어요. 골라 두었으니 바닥으로 끌어다 놓거나 [새 묶음]을 눌러 보세요.', + ); }; + const check = local ? null : (my?.check ?? null); + const changed = !!local || !!my?.changed; const commit = () => { - if (my?.check && !my.check.ok && v.options.invalidCommitPenalty === 'penalty3' && my.changed && my.check.fromRack > 0) { + const c = my?.check; + if (!local && c && !c.ok && v.options.invalidCommitPenalty === 'penalty3' && my?.changed && c.fromRack > 0) { setConfirm('commit'); return; } // The server refuses this commit (nothing changes in the view), so the "틀렸어요" feedback is local. - if (my?.check && !my.check.ok && (v.options.invalidCommitPenalty === 'reject' || !my.check.fromRack)) { + if (!local && c && !c.ok && (v.options.invalidCommitPenalty === 'reject' || !c.fromRack)) { sfx.bad(); haptic(80); setShake('table', 500); + setMsg(c.reason ?? ''); } - act({ type: 'commit', turn: v.turnNo }); + act({ type: 'commit', cells, turn: v.turnNo }); }; - const undoLike = (type: 'undoDraft' | 'resetDraft') => { + const reset = () => { sfx.whoosh(); - act({ type }); + setSel([]); + setMsg(''); + setLocal(null); + act({ type: 'resetDraft' }); }; const draw = () => { - if (my?.changed) setConfirm('draw'); + if (changed) setConfirm('draw'); else act({ type: v.poolCount ? 'draw' : 'pass' }); }; - const check = my?.check ?? null; - const viewDraft = v.draft; - const showingDraft = !!viewDraft; - const thinking = v.current && v.current !== me && v.draftEdits > 0; + const showChecks = mine || !!v.draft; const curName = v.current ? nick(players, v.current) : ''; - const selFromSets = sel.some((id) => inSets.has(id) && !onTable0.has(id)); + const othersMoving = !mine && !!v.current && v.draftEdits > 0; + const selOnBoard = sel.some((id) => onBoard.has(id) && !onTable0.has(id)); + const changedIds = new Set(v.lastChanged); + const dropCells = hand?.target?.kind === 'board' ? hand.target : null; + const setZ = (k: number) => { + const i = Math.max(0, Math.min(ZOOMS.length - 1, ZOOMS.indexOf(z) + k)); + setZoom(ZOOMS[i]!); + localStorage.setItem('rk-zoom', String(ZOOMS[i])); + }; return (
@@ -506,8 +880,15 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
- {showingDraft && !mine ? `${curName}님이 고민 중인 배치` : mine && my?.changed ? '바닥(확정 전)' : '바닥'} - {thinking && !showingDraft ? ` · ${curName}님이 생각 중…` : ''} + {mine ? (changed ? '바닥(완료 전)' : '바닥') : v.draft && othersMoving ? `${curName}님이 옮기는 중` : othersMoving ? `바닥 · ${curName}님이 생각 중…` : '바닥'} + + + + 남은 타일 {v.poolCount}장 @@ -516,81 +897,83 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr {mine && my && !my.melded && (
- 첫 등록 {check?.meldPoints ?? 0} / {v.options.initialMeldPoints}점 + 첫 등록 {meldNow} / {v.options.initialMeldPoints}점 - +
)} - {sets.length === 0 && !(mine && sel.length) &&

아직 바닥에 놓인 타일이 없어요.

} - {sets.map((d, i) => { - const info = mine || showingDraft ? (local ? null : viewDraft?.[i]) : null; - const n = info ? null : normalizeSet(d); - const ok = info ? info.ok : !!n; - const problem = info ? info.problem : n ? null : setProblem(d); - const jokerAs = info ? info.jokerAs : (n?.jokerAs ?? {}); - const tableSet = !mine && !showingDraft ? v.table[i] : undefined; - const changed = !!tableSet && v.lastChanged.includes(tableSet.id); - const label = `묶음 ${i + 1}: ${d.tileIds.map((id) => tileLabel(id, jokerAs[id])).join(', ')}${mine || showingDraft ? (ok ? ' (올바름)' : ` (고쳐야 함: ${problem ?? ''})`) : ''}`; - return ( -
- {mine && sel.length > 0 && ( - - )} - {d.tileIds.map((id) => ( - toggle(id) : undefined} /> - ))} - {mine && sel.length > 0 && ( - - )} - {(mine || showingDraft) && !ok && problem && {problem}} - {mine && info?.ambiguous && ( - - {info.kind === 'group' ? '같은 숫자 묶음으로 봐요' : '이어진 숫자로 봐요'} - - - )} -
- ); - })} - {mine && sel.length > 0 && ( - - )} +
+
+ {cells.length === 0 && !hand &&

{mine ? '받침대의 타일을 여기로 끌어다 놓으세요.' : '아직 바닥에 놓인 타일이 없어요.'}

} + {groups.map((g) => { + const fresh = !g.tableId; + const cls = showChecks && (fresh || !g.ok) ? (g.ok ? ' ok' : ' bad') : ''; + const flash = g.tableId && changedIds.has(g.tableId) && !v.draftEdits ? ' changed' : ''; + return ( +
+ {showChecks && !g.ok && g.problem && {g.problem}} +
+ ); + })} + {dropCells &&
} + {cells.map((x) => ( + toggle(x.id) : undefined} + onPointerDown={mine ? (e) => startPress(e, x.id) : undefined} + /> + ))} + {ghost && ghost.turn === v.turnNo && ( +
+ {ghost.tiles.map((id, i) => (id ? : ))} +
+ )} +
+
+
    + {groups.map((g, i) => ( +
  • + {`묶음 ${i + 1}: ${g.tileIds.map((id) => tileLabel(id, g.jokerAs[id])).join(', ')}${showChecks ? (g.ok ? ' (올바름)' : ` (고쳐야 함: ${g.problem ?? ''})`) : ''}`} +
  • + ))} +
{mine && ( <> -

+

{msg || (sel.length - ? `${sel.length}장 골랐어요. 놓을 곳(◀ ▶ 또는 새 묶음)을 누르세요.` - : my?.changed + ? `${sel.length}장 골랐어요. 바닥의 빈 칸을 누르거나 끌어다 놓으세요. [새 묶음]은 빈 곳에 따로 놓아요.` + : changed ? check?.ok - ? '좋아요! 확정을 누르면 차례가 끝나요.' + ? '좋아요! [완료]를 누르면 차례가 끝나요.' : (check?.reason ?? '') - : '타일을 눌러 고른 뒤 놓을 곳을 누르세요.')} + : '타일을 바닥으로 끌어다 놓으세요. 나란히 붙은 타일이 한 묶음이에요. 눌러서 고른 뒤 빈 칸을 눌러도 돼요.')}

- - - {selFromSets ? ( - ) : ( @@ -598,18 +981,18 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr 도와줘 )} - -
- {check?.ok ? '지금 확정할 수 있어요' : (check?.reason ?? '')} + {check?.ok ? '지금 완료할 수 있어요' : (check?.reason ?? '')} )} @@ -643,7 +1026,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr ))}
-
+
{rack.length === 0 && {my.rack.length ? '모두 바닥에 놓았어요.' : '타일이 없어요.'}} {rack.map((id) => { const k = fly ? fly.ids.indexOf(id) : -1; @@ -654,9 +1037,11 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr selected={sel.includes(id)} hint={hintIds.includes(id)} fresh={fresh.has(id)} + className={`${hand?.ids.includes(id) ? 'lifted' : ''}${mine ? ' grab' : ''}`} anim={k >= 0 ? 'anim-deal' : undefined} style={k >= 0 ? ({ '--from-y': '-140px', '--from-x': '0px', '--anim-delay': `${k * fly!.gap}ms` } as CSSProperties) : undefined} onClick={mine ? () => toggle(id) : undefined} + onPointerDown={mine ? (e) => startPress(e, id) : undefined} /> ); })} @@ -664,6 +1049,14 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
)} + {hand && ( +
+ {hand.ids.map((id) => ( + + ))} +
+ )} +

{announce}

@@ -679,11 +1072,11 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr )} {confirm === 'commit' && ( act({ type: 'commit', turn: v.turnNo })} + onConfirm={() => act({ type: 'commit', cells, turn: v.turnNo })} onClose={() => setConfirm(null)} /> )} @@ -793,7 +1186,7 @@ function logText(e: LogEntry, players: Record, me: string | case 'commit': return `${who} ${e.count}장을 냈어요.`; case 'timeoutCommit': - return `시간이 다 되어 ${who} 놓아 둔 ${e.count}장이 확정됐어요.`; + return `시간이 다 되어 ${who} 놓아 둔 ${e.count}장이 자동으로 완료됐어요.`; case 'draw': return `${who} 1장을 가져왔어요.`; case 'timeoutDraw': @@ -882,10 +1275,10 @@ function statusText(v: RummikubView, me: string | null, players: Record 0 ? ' · 생각 중' : ''}`; + return `${nick(players, v.current)}님 차례예요${v.draftEdits > 0 ? (v.draft ? ' · 타일 옮기는 중' : ' · 생각 중') : ''}`; } // ---------------------------------------------------------------- options @@ -924,8 +1317,8 @@ function Options({ value: o, onChange }: OptionsProps) { set({ turnSeconds: k === 'none' ? null : (Number(k) as 60 | 90 | 120 | 180) })} + options={[['30', '30초'], ['60', '1분'], ['90', '1분 30초'], ['120', '2분'], ['180', '3분'], ['none', '무제한']]} + onChange={(k) => set({ turnSeconds: k === 'none' ? null : (Number(k) as 30 | 60 | 90 | 120 | 180) })} /> @@ -939,14 +1332,14 @@ function Options({ value: o, onChange }: OptionsProps) { {more && ( <> - - set({ timeoutValidDraft })} /> + + set({ timeoutValidDraft })} /> - set({ invalidTimeoutPenalty })} /> + set({ invalidTimeoutPenalty })} /> - - set({ invalidCommitPenalty })} /> + + set({ invalidCommitPenalty })} /> set({ jokerPenalty })} /> @@ -954,8 +1347,8 @@ function Options({ value: o, onChange }: OptionsProps) { set({ initialMeldAllowExtend })} /> - - set({ showDraftToOthers })} /> + + set({ showDraftToOthers })} /> )} @@ -967,7 +1360,7 @@ function optionsSummary(o: RummikubOptions): string { const games = o.gamesPerMatch === 'players' ? '인원수만큼' : `${o.gamesPerMatch}판`; const t = o.turnSeconds; const sec = t === null ? null : t % 60 ? `${Math.floor(t / 60)}분 ${t % 60}초` : `${t / 60}분`; - return [o.initialMeldPoints ? `첫 등록 ${o.initialMeldPoints}점` : '첫 등록 점수 없음', sec ? `한 차례 ${sec}` : '시간 무제한', games, o.jokerPenalty === 50 ? '조커 50점' : '', o.showDraftToOthers ? '배치 공개' : ''] + return [o.initialMeldPoints ? `첫 등록 ${o.initialMeldPoints}점` : '첫 등록 점수 없음', sec ? `한 차례 ${sec}` : '시간 무제한', games, o.jokerPenalty === 50 ? '조커 50점' : '', o.showDraftToOthers ? '' : '옮기는 타일 비공개', o.invalidTimeoutPenalty === 3 ? '시간 초과 3장' : ''] .filter(Boolean) .join(' · '); } @@ -1009,7 +1402,7 @@ function Rules({ options }: { options?: RummikubOptions }) {

- 내 차례: 타일을 1장 이상 내고 "확정"을 누르거나, "한 장 가져오기"를 눌러요. 타일을 누른 뒤 놓을 곳(◀ 앞, ▶ 뒤, 새 묶음)을 누르면 옮겨져요. 확정할 때 바닥의 모든 묶음이 올바라야 해요. + 내 차례: 받침대의 타일을 바닥으로 끌어다 놓아요. 한 줄에 나란히 붙은 타일이 한 묶음이고, 한 칸 띄우면 다른 묶음이에요. 타일을 1장 이상 내고 "완료"를 누르거나, "한 장 가져오기"를 눌러요. 완료할 때 바닥의 모든 묶음이 올바라야 해요. "되돌리기"는 이번 차례에 옮긴 타일을 모두 처음 자리로 돌려요.

첫 등록:{' '} @@ -1017,11 +1410,13 @@ function Rules({ options }: { options?: RummikubOptions }) { {o?.initialMeldAllowExtend ? '첫 등록 차례에도 점수를 채운 뒤에는 바닥 묶음을 고칠 수 있어요.' : '첫 등록 전에는 바닥 묶음을 건드릴 수 없어요.'}

- 바닥 고치기: 첫 등록 뒤에는 바닥의 묶음을 쪼개고 합치고 옮겨서 내 타일을 끼워 넣을 수 있어요. 예를 들어 빨강 4-5-6-7-8 사이에 내 빨강 6을 넣어 4-5-6과 6-7-8로 나눌 수 있어요. 바닥 타일은 받침대로 가져올 수 없고, 조커를 빼 왔다면 같은 차례에 다시 바닥에 써야 해요. + 바닥 고치기: 첫 등록 뒤에는 바닥의 타일도 끌어다 묶음을 쪼개고 합칠 수 있어요. 타일 위에 놓으면 그 자리부터 오른쪽이 한 칸씩 밀려 사이에 끼워져요. 예를 들어 빨강 4-5-6-7-8 사이에 내 빨강 6을 넣어 4-5-6과 6-7-8로 나눌 수 있어요. 바닥 타일은 받침대로 가져올 수 없고, 조커를 빼 왔다면 같은 차례에 다시 바닥의 묶음에 써야 해요. 바닥 타일을 두 번 누르면 그 묶음을 통째로 골라요.

시간: {o?.turnSeconds === null ? '이 방은 시간 제한이 없어요. 연결이 끊긴 채로 오래 지나면' : `한 차례는 ${o ? `${o.turnSeconds}초` : '1분'}예요. 시간이 다 되면`}{' '} - {o?.timeoutValidDraft === 'revert' ? '놓아 둔 타일을 되돌리고 1장을 가져와요' : '올바르게 놓아 둔 타일은 자동으로 확정돼요'}. 묶음이 틀린 채로 끝나면 처음으로 되돌리고 {o?.invalidTimeoutPenalty ?? 3}장을 가져와요. + {o?.timeoutValidDraft === 'commit' + ? `올바르게 놓아 둔 타일은 자동으로 완료돼요. 묶음이 틀린 채로 끝나면 바닥이 처음으로 돌아가고 ${o.invalidTimeoutPenalty}장을 가져와요.` + : `[완료]를 누르지 않은 배치는 올발라도 모두 처음으로 돌아가고 1장을 가져와요${o?.invalidTimeoutPenalty === 3 ? '(묶음이 틀린 채였으면 3장)' : ''}.`}

점수: 누가 다 내려놓으면 나머지는 받침대 숫자 합만큼 빼고(조커 {o?.jokerPenalty ?? 30}점), 이긴 사람이 그만큼 더해요. 남은 타일이 없는데 아무도 못 내면 받침대 합이 가장 적은 사람이 이겨요. 점수는 이 방의 순위에만 써요. diff --git a/apps/web/src/games/rummikub/quick.tsx b/apps/web/src/games/rummikub/quick.tsx index 96bb167..e58bb89 100644 --- a/apps/web/src/games/rummikub/quick.tsx +++ b/apps/web/src/games/rummikub/quick.tsx @@ -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]])} - - {row(35, 94, [['O', 2], ['K', 9], ['R', 12], ['J', 0], ['B', 1], ['O', 13]])} + + ▲ 받침대에서 끌어다 놓기 + + + {row(35, 98, [['O', 2], ['K', 9], ['R', 12], ['J', 0], ['B', 1], ['O', 13]])} ), - 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: '첫 등록 뒤에는 바닥 타일도 끌어서 묶음을 쪼개고 합쳐 내 타일을 끼울 수 있어요. 시간 안에 [완료]하지 못하면 바닥이 처음으로 돌아가고 한 장 가져와요. 받침대를 먼저 비우면 이겨요.', }, ]; diff --git a/docs/13-decisions.md b/docs/13-decisions.md index 4af37be..c05eb9c 100644 --- a/docs/13-decisions.md +++ b/docs/13-decisions.md @@ -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) diff --git a/docs/games/rummikub.md b/docs/games/rummikub.md index d3d697a..e0884b7 100644 --- a/docs/games/rummikub.md +++ b/docs/games/rummikub.md @@ -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; // 조커 해석(표시·점수용) + 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; // 첫 등록 여부(공개) 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을 더했다. diff --git a/e2e/games.e2e.ts b/e2e/games.e2e.ts index 6249209..68f6208 100644 --- a/e2e/games.e2e.ts +++ b/e2e/games.e2e.ts @@ -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; } diff --git a/packages/games/src/rummikub/bot.test.ts b/packages/games/src/rummikub/bot.test.ts index 1de3f30..32b611d 100644 --- a/packages/games/src/rummikub/bot.test.ts +++ b/packages/games/src/rummikub/bot.test.ts @@ -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); diff --git a/packages/games/src/rummikub/bot.ts b/packages/games/src/rummikub/bot.ts index e67c9a6..889a451 100644 --- a/packages/games/src/rummikub/bot.ts +++ b/packages/games/src/rummikub/bot.ts @@ -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 }; @@ -35,9 +34,8 @@ export const rummikubBot: BotStrategy = ({ 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 = ({ 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 }; }; diff --git a/packages/games/src/rummikub/index.ts b/packages/games/src/rummikub/index.ts index 076df52..0085513 100644 --- a/packages/games/src/rummikub/index.ts +++ b/packages/games/src/rummikub/index.ts @@ -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 = (...vals: T[]) => z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral, z.ZodLiteral, ...z.ZodLiteral[]]); +/** 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; -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; + /** 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; 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; 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 => 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(); - 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(); + 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): { table: TableSet[]; changed: string[] } { const taken = new Set(); 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, 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 = {}; 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 & { 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 = { @@ -535,7 +623,7 @@ export const rummikub: GameDefinition, @@ -554,7 +642,7 @@ export const rummikub: GameDefinition [p, 0])), consecutivePasses: 0, lastDrawn: {}, @@ -582,26 +670,32 @@ export const rummikub: GameDefinition 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 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 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 1 ? 'penalty' : 'timeoutDraw', now, events); + } break; } } @@ -695,10 +794,11 @@ export const rummikub: GameDefinition 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 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 !s.ready.includes(p) && !s.left.includes(p)); @@ -783,15 +886,20 @@ export const rummikub: GameDefinition 0) acts.push({ type: 'commit' }); @@ -800,42 +908,50 @@ export const rummikub: GameDefinition 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 }[] = [...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]; diff --git a/packages/games/src/rummikub/rules.ts b/packages/games/src/rummikub/rules.ts index 37b2e7a..16949aa 100644 --- a/packages/games/src/rummikub/rules.ts +++ b/packages/games/src/rummikub/rules.ts @@ -277,3 +277,134 @@ export function extendSet(set: Pick, } 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, 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(); + prev.forEach((p, s) => p.tileIds.forEach((id, i) => where.set(id, { s, i }))); + const taken = new Set(); + const out: (Strip | null)[] = sets.map(() => null); + const anchor = (ids: readonly string[]): { r: number; c: number; overlap: number } | null => { + const counts = new Map(); + 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 }))]; +} diff --git a/packages/games/src/rummikub/rummikub.test.ts b/packages/games/src/rummikub/rummikub.test.ts index 1052f9b..549d30b 100644 --- a/packages/games/src/rummikub/rummikub.test.ts +++ b/packages/games/src/rummikub/rummikub.test.ts @@ -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 = {}, 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; + old.table = old.table.map(({ r: _r, c: _c, ...t }: Record) => 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 }).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[] = [ {}, - { 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)', () => {