원카드 화면: 따로 누르는 원카드 버튼(잡기 N초 세기), 카드 먹을 때 더미에서 한 장씩 날아가고 장마다 소리, 큰 벌칙은 판 흔들림·빨간 번쩍임, 공격 누적 숫자 세어 올라가기, 나눠 주기·섞기·내기·무늬/색 바꾸기 효과, 도움말·규칙·문서·E2E
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
385
apps/web/src/games/one-card/fx.tsx
Normal file
385
apps/web/src/games/one-card/fx.tsx
Normal file
@@ -0,0 +1,385 @@
|
||||
/**
|
||||
* 원카드 소리·움직임 (docs/games/one-card.md §9). Everything reacts to new public log lines, so other players' moves
|
||||
* sound and move too, and each change plays once (lines are handled by their `seq`).
|
||||
*/
|
||||
import { useLayoutEffect, useRef, useState, type RefObject } from 'react';
|
||||
import type { CardFace, LogEntry, OneCardView } from '@bg/games/one-card';
|
||||
import { haptic, noise, sfx, tone } from '../../lib/feedback';
|
||||
|
||||
export interface Banner {
|
||||
key: number;
|
||||
text: string;
|
||||
sub?: string;
|
||||
kind: 'attack' | 'call' | 'caught' | 'info' | 'win' | 'suit' | 'block';
|
||||
/** Text / glow colour for suit and colour changes. */
|
||||
color?: string;
|
||||
}
|
||||
|
||||
export interface Fx {
|
||||
banners: Banner[];
|
||||
/** Colour wash over the table (colour cards: the chosen colour). */
|
||||
flash: { key: number; color: string } | null;
|
||||
/** Bumps when the direction changes (the arrow spins). */
|
||||
spin: number;
|
||||
/** Bumps when the discard pile is shuffled back (the deck shakes). */
|
||||
shuffle: number;
|
||||
/** Where the newest discard flew in from (px, relative to the discard pile). */
|
||||
playFrom: { discard: number; x: number; y: number } | null;
|
||||
/** My cards that just arrived, with their animation delay (ms). */
|
||||
arrived: Record<string, number>;
|
||||
}
|
||||
|
||||
const SUIT_HEX: Record<string, string> = { S: '#111827', H: '#dc2626', D: '#dc2626', C: '#111827' };
|
||||
const SUIT_SYM: Record<string, string> = { S: '♠', H: '♥', D: '◆', C: '♣' };
|
||||
const SUIT_KO: Record<string, string> = { S: '스페이드', H: '하트', D: '다이아', C: '클로버' };
|
||||
const COLOR_HEX: Record<string, string> = { R: '#dc2626', Y: '#eab308', G: '#16a34a', B: '#2563eb' };
|
||||
const COLOR_KO: Record<string, string> = { R: '빨강', Y: '노랑', G: '초록', B: '파랑' };
|
||||
|
||||
const DRAW_WHY: Record<Extract<LogEntry, { t: 'draw' }>['why'], string> = {
|
||||
normal: '',
|
||||
attack: '공격을 못 막았어요',
|
||||
penalty: '원카드 벌칙!',
|
||||
bonus: '원카드를 먼저 외쳐서',
|
||||
draw2: '+2를 맞았어요',
|
||||
wild4: '색 바꾸기+4를 맞았어요',
|
||||
challenge: '의심 결과',
|
||||
start: '시작 카드가 +2',
|
||||
};
|
||||
|
||||
/** Game sounds built on the shared palette (no audio files). */
|
||||
const ocSound = {
|
||||
attack: (big: boolean) => {
|
||||
tone(196, 140, 'sawtooth', 0.05, 0, { slideTo: big ? 660 : 440 });
|
||||
noise(160, 0.1, 40, 'lowpass', 700);
|
||||
if (big) tone(880, 160, 'square', 0.04, 160);
|
||||
},
|
||||
reverse: () => {
|
||||
sfx.whoosh();
|
||||
tone(620, 130, 'triangle', 0.1, 0, { slideTo: 360 });
|
||||
tone(360, 130, 'triangle', 0.1, 140, { slideTo: 620 });
|
||||
},
|
||||
skip: () => {
|
||||
sfx.whoosh();
|
||||
tone(988, 60, 'square', 0.04, 80);
|
||||
tone(1318, 60, 'square', 0.04, 150);
|
||||
},
|
||||
suit: () => {
|
||||
sfx.pop();
|
||||
tone(1046, 140, 'triangle', 0.1, 110);
|
||||
tone(1568, 160, 'triangle', 0.08, 220);
|
||||
},
|
||||
call: () => {
|
||||
sfx.fanfare();
|
||||
noise(220, 0.06, 0, 'highpass', 3500);
|
||||
},
|
||||
block: () => {
|
||||
tone(1400, 50, 'square', 0.05);
|
||||
noise(90, 0.14, 0, 'bandpass', 3000, 3);
|
||||
sfx.good();
|
||||
},
|
||||
oneLeft: () => {
|
||||
tone(1175, 90, 'square', 0.05);
|
||||
tone(1175, 90, 'square', 0.05, 160);
|
||||
},
|
||||
};
|
||||
|
||||
const reduced = () => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
const rectOf = (root: HTMLElement, sel: string) => root.querySelector<HTMLElement>(sel)?.getBoundingClientRect() ?? null;
|
||||
const center = (r: DOMRect) => ({ x: r.left + r.width / 2, y: r.top + r.height / 2 });
|
||||
const seatSel = (p: string) => `[data-seat="${CSS.escape(p)}"]`;
|
||||
|
||||
/** Flight time of one card from the deck (ms). */
|
||||
const FLY_MS = 480;
|
||||
|
||||
/**
|
||||
* Card backs flying from the deck to a hand / seat, one after another (pure DOM, never blocks clicks). Each card
|
||||
* makes its own little sound as it leaves the deck and lands, a little higher each time, so a big penalty is heard
|
||||
* card by card. Returns the gap between cards (ms; 0 when nothing flew).
|
||||
*/
|
||||
function flyCards(root: HTMLElement, layer: HTMLElement, to: string, n: number, mode: OneCardView['mode'], delay0 = 0, quiet = false): number {
|
||||
const from = rectOf(root, '.oc-pile');
|
||||
const target = rectOf(root, to);
|
||||
const base = layer.getBoundingClientRect();
|
||||
const shown = Math.min(n, 12);
|
||||
const gap = shown > 8 ? 70 : shown > 4 ? 85 : 110;
|
||||
if (!quiet)
|
||||
for (let i = 0; i < shown; i++) {
|
||||
sfx.cardDeal(delay0 + i * gap);
|
||||
tone(520 + i * 45, 45, 'triangle', 0.05, delay0 + i * gap + FLY_MS - 40);
|
||||
}
|
||||
if (!from || !target || reduced()) return 0;
|
||||
const a = center(from);
|
||||
const b = center(target);
|
||||
const w = Math.min(from.width * 0.8, 64);
|
||||
for (let i = 0; i < shown; i++) {
|
||||
const el = document.createElement('div');
|
||||
el.className = `oc-fly${mode === 'uno-style' ? ' uno' : ''}`;
|
||||
el.style.width = `${w}px`;
|
||||
el.style.height = `${w * 1.4}px`;
|
||||
layer.appendChild(el);
|
||||
const x0 = a.x - base.left - w / 2;
|
||||
const y0 = a.y - base.top - (w * 1.4) / 2;
|
||||
// Spread the arrivals a little across the target so a pile of cards reads as many cards.
|
||||
const spread = Math.min(target.width * 0.35, 60) * (shown > 1 ? i / (shown - 1) - 0.5 : 0);
|
||||
const x1 = b.x - base.left - w / 2 + spread;
|
||||
const y1 = b.y - base.top - (w * 1.4) / 2;
|
||||
const lift = Math.min(90, Math.abs(y1 - y0) * 0.35 + 30);
|
||||
if (typeof el.animate !== 'function') {
|
||||
el.remove();
|
||||
continue;
|
||||
}
|
||||
const anim = el.animate(
|
||||
[
|
||||
{ transform: `translate(${x0}px, ${y0}px) rotate(0deg) scale(1)`, opacity: 1 },
|
||||
{ transform: `translate(${(x0 + x1) / 2}px, ${Math.min(y0, y1) - lift}px) rotate(${i % 2 ? 160 : -160}deg) scale(1.08)`, opacity: 1, offset: 0.55 },
|
||||
{ transform: `translate(${x1}px, ${y1}px) rotate(${i % 2 ? 350 : -350}deg) scale(0.7)`, opacity: 0.85 },
|
||||
],
|
||||
{ duration: FLY_MS, delay: delay0 + i * gap, easing: 'cubic-bezier(.3,.6,.35,1)', fill: 'both' },
|
||||
);
|
||||
anim.onfinish = () => el.remove();
|
||||
anim.oncancel = () => el.remove();
|
||||
}
|
||||
return gap;
|
||||
}
|
||||
|
||||
/** A big penalty lands: the table shakes and flashes red (the harder, the bigger). Starts when the first card lands. */
|
||||
function hitTable(root: HTMLElement, n: number, delay: number): void {
|
||||
const table = root.querySelector<HTMLElement>('.oc-table');
|
||||
if (!table || reduced() || typeof table.animate !== 'function') return;
|
||||
const d = Math.min(14, 4 + n);
|
||||
table.animate(
|
||||
[
|
||||
{ transform: 'none' },
|
||||
{ transform: `translateX(${-d}px) rotate(-1deg)`, offset: 0.15 },
|
||||
{ transform: `translateX(${d}px) rotate(1deg)`, offset: 0.35 },
|
||||
{ transform: `translateX(${-d * 0.6}px)`, offset: 0.55 },
|
||||
{ transform: `translateX(${d * 0.4}px)`, offset: 0.75 },
|
||||
{ transform: 'none' },
|
||||
],
|
||||
{ duration: 520, delay, easing: 'ease-out' },
|
||||
);
|
||||
table.animate(
|
||||
[{ boxShadow: '0 0 0 0 rgba(239,68,68,0), inset 0 0 0 0 rgba(239,68,68,0)' }, { boxShadow: '0 0 30px 10px rgba(239,68,68,.85), inset 0 0 70px 20px rgba(239,68,68,.6)', offset: 0.3 }, { boxShadow: '0 0 0 0 rgba(239,68,68,0), inset 0 0 0 0 rgba(239,68,68,0)' }],
|
||||
{ duration: 700, delay },
|
||||
);
|
||||
}
|
||||
|
||||
interface Ctx {
|
||||
view: OneCardView;
|
||||
me: string | null;
|
||||
nick: (id: string) => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Watches the view and returns what the board should show (banners, flashes, arrived cards). `root` is the board,
|
||||
* `layer` an absolutely positioned overlay inside it for the flying cards.
|
||||
*/
|
||||
export function useOneCardFx({ view: v, me, nick }: Ctx, root: RefObject<HTMLDivElement | null>, layer: RefObject<HTMLDivElement | null>): Fx {
|
||||
const [fx, setFx] = useState<Fx>({ banners: [], flash: null, spin: 0, shuffle: 0, playFrom: null, arrived: {} });
|
||||
const seen = useRef<number | null>(null);
|
||||
const hand = useRef<Set<string> | null>(null);
|
||||
const round = useRef(v.round);
|
||||
const keyRef = useRef(1);
|
||||
const timers = useRef<number[]>([]);
|
||||
|
||||
useLayoutEffect(() => () => timers.current.forEach((t) => clearTimeout(t)), []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const lastSeq = v.log.length ? v.log[v.log.length - 1]!.seq : 0;
|
||||
const myHand = v.my?.hand ?? [];
|
||||
const first = seen.current === null;
|
||||
const fresh = first ? [] : v.log.filter((e) => e.seq > seen.current!);
|
||||
seen.current = Math.max(seen.current ?? 0, lastSeq);
|
||||
const banners: Banner[] = [];
|
||||
const next: Partial<Fx> = {};
|
||||
const sounds = new Set<string>();
|
||||
let drawGap = 0;
|
||||
let myDraw = 0;
|
||||
const banner = (b: Omit<Banner, 'key'>) => banners.push({ ...b, key: keyRef.current++ });
|
||||
const who = (p: string) => (p === me ? '내가' : `${nick(p)}님이`);
|
||||
const rootEl = root.current;
|
||||
const layerEl = layer.current;
|
||||
let draws = 0;
|
||||
let myAt = 0;
|
||||
for (const e of fresh) {
|
||||
switch (e.t) {
|
||||
case 'play': {
|
||||
sounds.add('play');
|
||||
const c = e.cards[0] as CardFace;
|
||||
if (rootEl) {
|
||||
const from = rectOf(rootEl, e.p === me ? '.oc-hand' : seatSel(e.p));
|
||||
const to = rectOf(rootEl, '.oc-discard');
|
||||
if (from && to) {
|
||||
const a = center(from);
|
||||
const b = center(to);
|
||||
next.playFrom = { discard: v.discardCount, x: a.x - b.x, y: a.y - b.y };
|
||||
}
|
||||
}
|
||||
if (c.kind === 'std' && c.rank === 7 && e.suit) {
|
||||
sounds.add('suit');
|
||||
banner({ text: `${SUIT_SYM[e.suit]}`, sub: `${who(e.p)} ${SUIT_KO[e.suit]}로 바꿨어요`, kind: 'suit', color: SUIT_HEX[e.suit] });
|
||||
} else if (e.color) {
|
||||
sounds.add('suit');
|
||||
next.flash = { key: keyRef.current++, color: COLOR_HEX[e.color]! };
|
||||
banner({ text: COLOR_KO[e.color]!, sub: `${who(e.p)} 색을 바꿨어요`, kind: 'suit', color: COLOR_HEX[e.color] });
|
||||
}
|
||||
if (c.kind === 'joker') {
|
||||
sounds.add('bigAttack');
|
||||
banner({ text: '조커!', sub: `+${v.pendingAttack}장 공격`, kind: 'attack' });
|
||||
} else if ((c.kind === 'std' && (c.rank === 1 || c.rank === 2)) || c.kind === 'draw2' || c.kind === 'wild4') {
|
||||
if (v.pendingAttack > 0) sounds.add(v.pendingAttack >= 5 ? 'bigAttack' : 'attack');
|
||||
}
|
||||
if (c.kind === 'std' && c.rank === 13 && v.extraTurn && v.current === e.p) banner({ text: 'K! 한 번 더', kind: 'info' });
|
||||
if (e.p === me && myHand.length === 1 && v.oneCardWindow?.player === me && !v.oneCardWindow.declared) {
|
||||
sounds.add('oneLeft');
|
||||
haptic([40, 40, 40]);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'draw': {
|
||||
if (e.n <= 0) break;
|
||||
// Several eaters at once (원카드 보너스): one after another, not on top of each other.
|
||||
const at = 260 * draws++;
|
||||
if (rootEl && layerEl) {
|
||||
const gap = flyCards(rootEl, layerEl, e.p === me ? '.oc-hand' : seatSel(e.p), e.n, v.mode, at);
|
||||
if (e.p === me) {
|
||||
drawGap = gap;
|
||||
myAt = at;
|
||||
}
|
||||
const big = e.n >= 4 || e.why === 'penalty';
|
||||
if (big) hitTable(rootEl, e.n, at + FLY_MS - 80);
|
||||
}
|
||||
if (e.p === me) myDraw += e.n;
|
||||
if (e.n >= 2 || e.why === 'penalty' || e.why === 'bonus') {
|
||||
banner({ text: `+${e.n}장`, sub: `${who(e.p)} 먹어요${DRAW_WHY[e.why] ? ` · ${DRAW_WHY[e.why]}` : ''}`, kind: e.n >= 4 || e.why === 'penalty' ? 'attack' : 'info' });
|
||||
if (e.n >= 5 || e.why === 'penalty') sounds.add('alarm');
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'declare':
|
||||
sounds.add('call');
|
||||
banner({ text: '원카드!', sub: `${who(e.p)} 외쳤어요`, kind: 'call' });
|
||||
break;
|
||||
case 'caught':
|
||||
sounds.add('caught');
|
||||
banner({ text: '잡았다!', sub: `${who(e.by)} 먼저 외쳐서 ${who(e.p)} ${e.n}장`, kind: 'caught' });
|
||||
break;
|
||||
case 'blocked':
|
||||
sounds.add('block');
|
||||
banner({ text: '막았다!', sub: `${nick(e.p)}님이 3으로 공격을 막았어요`, kind: 'block' });
|
||||
break;
|
||||
case 'reverse':
|
||||
sounds.add('reverse');
|
||||
next.spin = (next.spin ?? fx.spin) + 1;
|
||||
banner({ text: '⇄ 방향 바뀜', kind: 'info' });
|
||||
break;
|
||||
case 'skip':
|
||||
sounds.add('skip');
|
||||
banner({ text: '건너뛰기!', sub: `${nick(e.p)}님 차례를 건너뛰어요`, kind: 'info' });
|
||||
break;
|
||||
case 'reshuffle':
|
||||
sounds.add('shuffle');
|
||||
next.shuffle = (next.shuffle ?? fx.shuffle) + 1;
|
||||
break;
|
||||
case 'out':
|
||||
if (v.phase !== 'finished') sounds.add('out');
|
||||
banner({ text: `${e.place}등!`, sub: `${who(e.p)} 카드를 모두 냈어요`, kind: 'win' });
|
||||
break;
|
||||
case 'bankrupt':
|
||||
sounds.add('bad');
|
||||
banner({ text: '파산!', sub: `${who(e.p)} 탈락했어요`, kind: 'caught' });
|
||||
break;
|
||||
case 'challenge':
|
||||
sounds.add(e.illegal ? 'good' : 'bad');
|
||||
banner({ text: e.illegal ? '의심 성공!' : '의심 실패', kind: e.illegal ? 'block' : 'caught' });
|
||||
break;
|
||||
case 'round':
|
||||
banner({ text: `${e.round}판 끝`, sub: e.winner ? `${nick(e.winner)}님 +${e.points}점` : undefined, kind: 'win' });
|
||||
break;
|
||||
}
|
||||
}
|
||||
// A new round (or the first deal of the game) deals my cards in.
|
||||
// The first look at a game nobody has moved in yet, or a new round (색깔 카드 점수제): deal everyone in.
|
||||
const untouched = !v.log.some((e) => e.t === 'play' || e.t === 'pass' || (e.t === 'draw' && e.why !== 'start'));
|
||||
const dealing = (first && untouched && v.phase !== 'finished') || v.round !== round.current;
|
||||
round.current = v.round;
|
||||
const prev = hand.current;
|
||||
hand.current = new Set(myHand.map((c) => c.id));
|
||||
const arrived: Record<string, number> = {};
|
||||
if (dealing) {
|
||||
sfx.shuffle();
|
||||
next.shuffle = (next.shuffle ?? fx.shuffle) + 1;
|
||||
const seats = v.seats.filter((s) => s.status === 'playing');
|
||||
// A few backs to every seat in turn (quiet: one shared dealing sound), then my own cards land one by one.
|
||||
if (rootEl && layerEl) seats.forEach((s, k) => flyCards(rootEl, layerEl, s.id === me ? '.oc-hand' : seatSel(s.id), 3, v.mode, 300 + k * 140, true));
|
||||
const start = 300 + seats.length * 140;
|
||||
myHand.forEach((c, i) => (arrived[c.id] = start + i * 70));
|
||||
for (let i = 0; i < Math.min(seats.length * 3, 14); i++) sfx.cardDeal(300 + i * 70);
|
||||
} else if (prev && myDraw > 0) {
|
||||
const gap = drawGap || 90;
|
||||
let i = 0;
|
||||
for (const c of myHand) if (!prev.has(c.id)) arrived[c.id] = myAt + FLY_MS - 100 + i++ * gap;
|
||||
}
|
||||
if (Object.keys(arrived).length) next.arrived = arrived;
|
||||
|
||||
if (sounds.has('play')) sfx.cardPlay();
|
||||
if (sounds.has('bigAttack')) ocSound.attack(true);
|
||||
else if (sounds.has('attack')) ocSound.attack(false);
|
||||
if (sounds.has('suit')) ocSound.suit();
|
||||
if (sounds.has('reverse')) ocSound.reverse();
|
||||
if (sounds.has('skip')) ocSound.skip();
|
||||
if (sounds.has('block')) ocSound.block();
|
||||
if (sounds.has('shuffle')) sfx.shuffle();
|
||||
if (sounds.has('caught')) sfx.alarm();
|
||||
else if (sounds.has('alarm')) sfx.alarm();
|
||||
if (sounds.has('call')) ocSound.call();
|
||||
if (sounds.has('oneLeft')) ocSound.oneLeft();
|
||||
if (sounds.has('out')) sfx.fanfare();
|
||||
if (sounds.has('good')) sfx.good();
|
||||
if (sounds.has('bad')) sfx.bad();
|
||||
if (myDraw >= 2) haptic([30, 30, 30]);
|
||||
|
||||
if (banners.length || Object.keys(next).length) {
|
||||
setFx((f) => ({ ...f, ...next, banners: [...f.banners, ...banners].slice(-3) }));
|
||||
for (const b of banners) {
|
||||
const t = window.setTimeout(() => setFx((f) => ({ ...f, banners: f.banners.filter((x) => x.key !== b.key) })), 1700);
|
||||
timers.current.push(t);
|
||||
}
|
||||
}
|
||||
timers.current = timers.current.slice(-20);
|
||||
}, [v.log.length ? v.log[v.log.length - 1]!.seq : 0, v.round, v.my?.hand.length]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
return fx;
|
||||
}
|
||||
|
||||
export const FX_CSS = `
|
||||
.oc { position: relative; }
|
||||
.oc-fxlayer { position: absolute; inset: 0; pointer-events: none; overflow: hidden; z-index: 30; }
|
||||
.oc-fly { position: absolute; left: 0; top: 0; border-radius: 8px; border: 3px solid #fff; box-shadow: 0 6px 14px rgba(0,0,0,.35);
|
||||
background: repeating-linear-gradient(45deg, #1e3a8a 0 6px, #2547b8 6px 12px); will-change: transform; }
|
||||
.oc-fly.uno { background: radial-gradient(ellipse 38% 48% at center, #dc2626 0 98%, transparent 100%), #111827; }
|
||||
.oc-banners { position: absolute; left: 0; right: 0; top: 50%; transform: translateY(-50%); display: flex; flex-direction: column; align-items: center; gap: 6px;
|
||||
pointer-events: none; z-index: 31; }
|
||||
.oc-banner { display: flex; flex-direction: column; align-items: center; gap: 2px; padding: 6px 22px; border-radius: 18px; color: #fff; background: rgba(17,24,39,.86);
|
||||
box-shadow: 0 10px 28px rgba(0,0,0,.4); text-align: center; max-width: 92%; }
|
||||
.oc-banner b { font-size: clamp(1.9rem, 7vw, 3.2rem); font-weight: 900; line-height: 1.1; letter-spacing: .02em; text-shadow: 0 3px 0 rgba(0,0,0,.35); }
|
||||
.oc-banner span { font-size: .95rem; font-weight: 700; opacity: .95; }
|
||||
.oc-banner.attack { background: linear-gradient(135deg, #b91c1c, #f97316); }
|
||||
.oc-banner.attack b { font-size: clamp(2.4rem, 10vw, 4.4rem); }
|
||||
.oc-banner.call { background: linear-gradient(135deg, #f59e0b, #fde047); color: #1f2937; }
|
||||
.oc-banner.call b { text-shadow: 0 3px 0 rgba(255,255,255,.5); }
|
||||
.oc-banner.caught { background: linear-gradient(135deg, #7f1d1d, #dc2626); }
|
||||
.oc-banner.win { background: linear-gradient(135deg, #15803d, #22c55e); }
|
||||
.oc-banner.block { background: linear-gradient(135deg, #1d4ed8, #38bdf8); }
|
||||
.oc-banner.suit { background: #fffef9; color: var(--suit, #111827); border: 4px solid var(--suit, #111827); }
|
||||
.oc-flash { position: absolute; inset: -8px; border-radius: 24px; pointer-events: none; animation: oc-flash .7s ease-out both; z-index: 1; }
|
||||
@keyframes oc-flash { 0% { box-shadow: inset 0 0 0 0 var(--c), 0 0 0 0 var(--c); opacity: 1; } 40% { box-shadow: inset 0 0 60px 16px var(--c), 0 0 26px 6px var(--c); } 100% { box-shadow: inset 0 0 0 0 var(--c), 0 0 0 0 var(--c); opacity: 0; } }
|
||||
.oc-spin { display: inline-block; animation: oc-spin .6s cubic-bezier(.3,.7,.3,1) both; }
|
||||
@keyframes oc-spin { from { transform: rotate(-360deg) scale(1.6); } }
|
||||
.oc-attack { position: relative; }
|
||||
.oc-attack.grow { animation: anim-pop .32s cubic-bezier(.3,1.6,.5,1) both, oc-burn 1.2s ease-in-out .32s infinite; }
|
||||
@keyframes oc-burn { 50% { box-shadow: 0 0 0 4px rgba(249,115,22,.55), 0 0 22px rgba(239,68,68,.8); } }
|
||||
.oc-attack small { display: block; font-size: .8rem; font-weight: 800; opacity: .9; }
|
||||
.oc-card.oc-in { animation: anim-deal .38s cubic-bezier(.2,.8,.3,1.15) backwards; animation-delay: var(--anim-delay, 0ms); --from-y: -90px; }
|
||||
.oc-pile.shake { animation: anim-shake .45s ease both; }
|
||||
`;
|
||||
@@ -47,6 +47,17 @@ test('원카드: 7로 정한 무늬, 원카드 잡기', () => {
|
||||
state.hands[other] = [state.hands[other][0]];
|
||||
expect(helpNow(view(state, other), other, users)).toContain('[원카드!] 버튼을 빨리 눌러요');
|
||||
expect(helpNow(view(state, cur), cur, users)).toContain(`${nickOf(other)}님이 1장 남았는데`);
|
||||
expect(helpNow(view(state, cur), cur, users)).toContain('2초가 지나면 [원카드!]를 먼저 눌러 잡을 수 있어요');
|
||||
});
|
||||
|
||||
test('원카드: 끝에서 두 번째 카드를 낼 때는 원카드를 따로 누르라고 안내', () => {
|
||||
const { state } = setupGame('one-card', 3);
|
||||
const cur = state.current as string;
|
||||
state.discard.push({ id: 'H8', kind: 'std', suit: 'H', rank: 8 });
|
||||
state.hands[cur] = [{ id: 'H9', kind: 'std', suit: 'H', rank: 9 }, { id: 'C5', kind: 'std', suit: 'C', rank: 5 }];
|
||||
const t = helpNow(view(state, cur), cur, users);
|
||||
expect(t).toContain('카드를 낸 다음 동그란 [원카드!] 버튼을 따로 꼭 눌러요');
|
||||
expect(t).not.toContain('내면서');
|
||||
});
|
||||
|
||||
test('색깔 카드: 색 바꾸기+4 의심하기', () => {
|
||||
@@ -68,7 +79,9 @@ test('원카드: 끝나면 결과 안내', () => {
|
||||
let { state: s } = setupGame('one-card', 2, { handSize: 5 });
|
||||
for (let i = 0; i < 2000 && !def.result(s); i++) {
|
||||
const actor = def.activePlayers(s)[0]!;
|
||||
s = applyAction('one-card', s, actor, def.legalActions!(s, actor)[0]);
|
||||
// The clock here stands still, so a catch (only after the protection time) is never allowed: skip it.
|
||||
const legal = def.legalActions!(s, actor).filter((a) => def.validate(s, actor, a, { now: 1_700_000_100_000 }).ok);
|
||||
s = applyAction('one-card', s, actor, legal[0]);
|
||||
}
|
||||
expect(def.result(s)).toBeTruthy();
|
||||
expect(helpNow(view(s, 'A'), 'A', usersOf(['A', 'B']))).toContain('게임이 끝났어요');
|
||||
|
||||
@@ -63,7 +63,7 @@ function myTurn(v: OneCardView): string[] {
|
||||
lines.push('낼 수 있는 카드가 없어요. [1장 먹기]를 누르거나 카드 더미를 눌러 주세요.');
|
||||
}
|
||||
if (hand.length === 1 && legal === 0 && v.mode === 'classic' && v.options.lastCardRule !== 'none') lines.push(LAST_CARD[v.options.lastCardRule]);
|
||||
if (hand.length === 2 && !v.options.autoDeclare && legal > 0) lines.push('내고 나면 1장이 남아요. [내면서 원카드 외치기]에 체크돼 있는지 확인해요.');
|
||||
if (hand.length === 2 && !v.options.autoDeclare && legal > 0) lines.push('내고 나면 1장이 남아요. 카드를 낸 다음 동그란 [원카드!] 버튼을 따로 꼭 눌러요.');
|
||||
return lines;
|
||||
}
|
||||
|
||||
@@ -83,11 +83,12 @@ export function helpNow(v: OneCardView, me: string | null, players: Record<strin
|
||||
return `${res}${target}\n다른 사람이 준비하기를 기다리는 중이에요.`;
|
||||
}
|
||||
|
||||
// Someone with one card has not called "원카드!" yet: anyone still in the game can press the button.
|
||||
// Someone with one card has not called "원카드!" yet: the owner right away, anyone else after the protection time.
|
||||
const catchLine = (() => {
|
||||
if (!my?.canDeclare || !w || w.declared) return '';
|
||||
if (w.player === me) return `카드가 1장 남았어요! 동그란 [원카드!] 버튼을 빨리 눌러요. 다른 사람이 먼저 누르면 ${v.penalty}장을 먹어요.`;
|
||||
return `${nm(players, w.player)}이 1장 남았는데 아직 원카드를 안 외쳤어요. [원카드!]를 먼저 누르면 ${nm(players, w.player)}이 ${v.penalty}장을 먹어요.`;
|
||||
const grace = v.options.oneCardGrace;
|
||||
if (w.player === me) return `카드가 1장 남았어요! 동그란 [원카드!] 버튼을 빨리 눌러요. ${grace}초가 지나면 다른 사람이 먼저 눌러 잡을 수 있고, 잡히면 ${v.penalty}장을 먹어요.`;
|
||||
return `${nm(players, w.player)}이 1장 남았는데 아직 원카드를 안 외쳤어요. ${grace}초가 지나면 [원카드!]를 먼저 눌러 잡을 수 있어요. 잡으면 ${nm(players, w.player)}이 ${v.penalty}장을 먹어요.`;
|
||||
})();
|
||||
const withCatch = (lines: string[]) => (catchLine ? [catchLine, ...lines] : lines).join('\n');
|
||||
|
||||
|
||||
@@ -3,14 +3,15 @@ import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type
|
||||
import type { Card, CardFace, Color, LogEntry, OneCardOptions, OneCardView, SeatView, Suit } from '@bg/games/one-card';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, Sheet } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { PlayingCard } from '../../components/cards/PlayingCard';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { haptic, sounds, tone } from '../../lib/feedback';
|
||||
import { useSeatRows } from '../../lib/seat-rows';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { COLOR_HEX, COLOR_INK, COLOR_KO, ColorCardArt, colorCardLabel, patternName } from './ColorCard';
|
||||
import { FX_CSS, useOneCardFx, type Fx } from './fx';
|
||||
|
||||
const SUITS: Suit[] = ['S', 'H', 'D', 'C'];
|
||||
const COLORS: Color[] = ['R', 'Y', 'G', 'B'];
|
||||
@@ -71,7 +72,7 @@ const CSS = `
|
||||
.oc-pile .cnt { position: absolute; right: -6px; bottom: -8px; background: #111827; color: #fff; border-radius: 999px; padding: 0 8px; font-weight: 800; font-size: .85rem; }
|
||||
.oc-discard { position: relative; width: calc(var(--pw) * 1.12); height: calc(var(--pw) * 1.12 * 1.4); }
|
||||
.oc-discard > .oc-face { position: absolute; inset: 0; }
|
||||
.oc-discard > .oc-face.top { animation: oc-fly .28s ease-out; }
|
||||
.oc-discard > .oc-face.top { animation: oc-fly .32s cubic-bezier(.2,.8,.3,1.1); }
|
||||
.oc-discard[data-drop='true'] { outline: 3px dashed #fde047; outline-offset: 4px; border-radius: 10px; }
|
||||
.oc-info { display: flex; flex-direction: column; gap: 6px; align-items: flex-start; min-width: 0; text-shadow: 0 1px 2px rgba(0,0,0,.5); }
|
||||
.oc-info .row { gap: 6px; }
|
||||
@@ -101,6 +102,11 @@ const CSS = `
|
||||
font-weight: 900; font-size: 1.02rem; line-height: 1.1; padding: 0; cursor: pointer; box-shadow: 0 3px 8px rgba(0,0,0,.25); }
|
||||
.oc-onebtn:disabled { background: var(--surface-2); color: var(--text-sub); border-color: var(--border); box-shadow: none; cursor: not-allowed; }
|
||||
.oc-onebtn:not(:disabled) { animation: oc-shake .3s ease-in-out 3; }
|
||||
.oc-onebtn.urgent { animation: oc-shake .3s ease-in-out 3, oc-urgent 1s ease-in-out .9s infinite; }
|
||||
.oc-onebtn.wait { font-size: .85rem; }
|
||||
@keyframes oc-urgent { 50% { transform: scale(1.1); box-shadow: 0 0 0 6px rgba(251,191,36,.55), 0 0 22px rgba(245,158,11,.9); } }
|
||||
.oc-shuf { display: block; width: 100%; height: 100%; animation: oc-shuffle .6s ease both; }
|
||||
@keyframes oc-shuffle { 20% { transform: translateX(-10px) rotate(-8deg); } 40% { transform: translateX(10px) rotate(8deg); } 60% { transform: translateX(-6px) rotate(-4deg); } 80% { transform: translateY(-6px); } }
|
||||
.oc-tools { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; }
|
||||
.oc-tools .segmented button { min-height: 40px; padding: 0 12px; }
|
||||
.oc-panel { background: var(--surface); border-radius: 16px; box-shadow: var(--shadow); padding: 12px; display: flex; flex-direction: column; gap: 8px; }
|
||||
@@ -112,7 +118,7 @@ const CSS = `
|
||||
.oc-log { list-style: none; margin: 8px 0 0; padding: 0; display: grid; gap: 3px; max-height: 240px; overflow: auto; }
|
||||
.oc-rules td, .oc-rules th { padding: 4px 6px; text-align: left; vertical-align: middle; border-bottom: 1px solid var(--border); }
|
||||
.oc-rules .oc-face { width: 34px; height: 48px; }
|
||||
@keyframes oc-fly { from { transform: translate(-40px, 30px) scale(.8); opacity: .3; } to { transform: none; opacity: 1; } }
|
||||
@keyframes oc-fly { from { transform: translate(var(--fx, -40px), var(--fy, 30px)) rotate(-25deg) scale(.75); opacity: .4; } }
|
||||
@keyframes oc-pop { 0% { transform: scale(.6); } 70% { transform: scale(1.12); } 100% { transform: scale(1); } }
|
||||
@keyframes oc-shake { 0%,100% { transform: rotate(0); } 25% { transform: rotate(-8deg); } 75% { transform: rotate(8deg); } }
|
||||
/* PC/tablet: many players stack into even rows (9 → 5 + 4) instead of scrolling sideways. Phones keep one swipeable row. */
|
||||
@@ -158,7 +164,7 @@ function SeatChip({ s, v, players, me, deadline }: { s: SeatView; v: OneCardView
|
||||
const u = userOf(players, s.id);
|
||||
const place = v.result?.players.find((p) => p.player === s.id)?.rank;
|
||||
return (
|
||||
<li className={`oc-seat${s.isTurn ? ' turn' : ''}${s.status === 'bankrupt' || s.status === 'left' ? ' gone' : ''}`} aria-label={seatLabel(s, players, me, v)}>
|
||||
<li className={`oc-seat${s.isTurn ? ' turn' : ''}${s.status === 'bankrupt' || s.status === 'left' ? ' gone' : ''}`} data-seat={s.id} aria-label={seatLabel(s, players, me, v)}>
|
||||
<div className="row" style={{ gap: 6, flexWrap: 'nowrap' }}>
|
||||
<Avatar user={u} size={24} />
|
||||
<span className="nm">{u.nickname}</span>
|
||||
@@ -186,8 +192,43 @@ function SeatChip({ s, v, players, me, deadline }: { s: SeatView; v: OneCardView
|
||||
|
||||
// ---------------------------------------------------------------- table
|
||||
|
||||
function TableArea({ v, players, canDraw, onDraw, onDropCard }: { v: OneCardView; players: Record<string, PublicUser>; canDraw: boolean; onDraw: () => void; onDropCard: (id: string) => void }) {
|
||||
/** The stacked attack: counts up card by card (with a rising tick) when someone adds to it, and grows with the count. */
|
||||
function AttackCount({ n, uno }: { n: number; uno: boolean }) {
|
||||
const [shown, setShown] = useState(n);
|
||||
const prev = useRef(n);
|
||||
useEffect(() => {
|
||||
const from = prev.current;
|
||||
prev.current = n;
|
||||
if (n <= from) {
|
||||
setShown(n);
|
||||
return;
|
||||
}
|
||||
let k = Math.max(from, 1);
|
||||
setShown(k);
|
||||
if (k >= n) return;
|
||||
const id = window.setInterval(
|
||||
() => {
|
||||
k += 1;
|
||||
setShown(k);
|
||||
tone(320 + k * 45, 55, 'square', 0.035);
|
||||
if (k >= n) window.clearInterval(id);
|
||||
},
|
||||
Math.max(45, Math.min(110, 420 / (n - from))),
|
||||
);
|
||||
return () => window.clearInterval(id);
|
||||
}, [n]);
|
||||
if (n <= 0) return null;
|
||||
return (
|
||||
<span key={shown} className="oc-attack grow" aria-live="polite" aria-label={`${uno ? '먹을 카드' : '공격'} ${n}장`} style={{ fontSize: `${1.4 + Math.min(shown, 15) * 0.07}rem` }}>
|
||||
+{shown}장!
|
||||
<small aria-hidden>{uno ? '먹을 카드' : '공격 누적'}</small>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function TableArea({ v, players, canDraw, onDraw, onDropCard, fx }: { v: OneCardView; players: Record<string, PublicUser>; canDraw: boolean; onDraw: () => void; onDropCard: (id: string) => void; fx: Fx }) {
|
||||
const [over, setOver] = useState(false);
|
||||
const from = fx.playFrom && fx.playFrom.discard === v.discardCount ? fx.playFrom : null;
|
||||
const pw = 'clamp(64px, 9vw, 92px)';
|
||||
const recent = v.recent;
|
||||
const top = recent[recent.length - 1];
|
||||
@@ -202,7 +243,9 @@ function TableArea({ v, players, canDraw, onDraw, onDropCard }: { v: OneCardView
|
||||
onClick={onDraw}
|
||||
aria-label={`카드 더미 ${v.drawPileCount}장${canDraw ? `. 눌러서 ${drawText}` : ''}`}
|
||||
>
|
||||
<Face card={null} mode={v.mode} />
|
||||
<span key={fx.shuffle} className={fx.shuffle ? 'oc-shuf' : undefined} style={{ display: 'block', width: '100%', height: '100%' }}>
|
||||
<Face card={null} mode={v.mode} />
|
||||
</span>
|
||||
<span className="cnt" aria-hidden>
|
||||
{v.drawPileCount}
|
||||
</span>
|
||||
@@ -228,21 +271,23 @@ function TableArea({ v, players, canDraw, onDraw, onDropCard }: { v: OneCardView
|
||||
const last = i === arr.length - 1;
|
||||
const rot = last ? 0 : (i - arr.length + 1) * 9;
|
||||
return (
|
||||
<span key={`${v.discardCount - arr.length + i}`} className={`oc-face${last ? ' top' : ''}`} style={{ transform: `rotate(${rot}deg) translate(${rot * 0.6}px, 0)` }}>
|
||||
<span
|
||||
key={`${v.discardCount - arr.length + i}`}
|
||||
className={`oc-face${last ? ' top' : ''}`}
|
||||
style={{ transform: `rotate(${rot}deg) translate(${rot * 0.6}px, 0)`, ...(last && from ? { '--fx': `${Math.round(from.x)}px`, '--fy': `${Math.round(from.y)}px` } : {}) } as CSSProperties}
|
||||
>
|
||||
<Face card={c} mode={v.mode} />
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="oc-info">
|
||||
{v.pendingAttack > 0 && (
|
||||
<span key={v.pendingAttack} className="oc-attack" aria-live="polite">
|
||||
+{v.pendingAttack}장!
|
||||
</span>
|
||||
)}
|
||||
<AttackCount n={v.pendingAttack} uno={v.mode === 'uno-style'} />
|
||||
<div className="row">
|
||||
<span className="oc-dir" data-dir={v.direction} aria-label={v.direction === 1 ? '진행 방향: 시계 방향' : '진행 방향: 반대 방향'}>
|
||||
<b aria-hidden>↻</b>
|
||||
<b key={fx.spin} className={fx.spin ? 'oc-spin' : undefined} aria-hidden>
|
||||
↻
|
||||
</b>
|
||||
{v.direction === 1 ? '시계 방향' : '반대 방향'}
|
||||
</span>
|
||||
{v.extraTurn && <span className="oc-chip">K: 한 번 더</span>}
|
||||
@@ -272,6 +317,15 @@ function TableArea({ v, players, canDraw, onDraw, onDropCard }: { v: OneCardView
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{fx.flash && <div key={fx.flash.key} className="oc-flash" style={{ '--c': fx.flash.color } as CSSProperties} aria-hidden />}
|
||||
<div className="oc-banners" aria-hidden>
|
||||
{fx.banners.map((b) => (
|
||||
<div key={b.key} className={`oc-banner anim-banner ${b.kind}`} style={b.color ? ({ '--suit': b.color } as CSSProperties) : undefined}>
|
||||
<b>{b.text}</b>
|
||||
{b.sub && <span>{b.sub}</span>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -297,11 +351,10 @@ interface PickState {
|
||||
kind: 'suit' | 'color';
|
||||
}
|
||||
|
||||
function MyHand({ v, act, pending, players }: { v: OneCardView; act: (a: unknown) => void; pending: boolean; players: Record<string, PublicUser> }) {
|
||||
function MyHand({ v, act, pending, players, arrived }: { v: OneCardView; act: (a: unknown) => void; pending: boolean; players: Record<string, PublicUser>; arrived: Record<string, number> }) {
|
||||
const my = v.my!;
|
||||
const [sortBy, setSortBy] = useState<'suit' | 'rank'>('suit');
|
||||
const [sel, setSel] = useState<string[]>([]);
|
||||
const [declare, setDeclare] = useState(true);
|
||||
const [hints, setHints] = useState(true);
|
||||
const [pick, setPick] = useState<PickState | null>(null);
|
||||
const [note, setNote] = useState('');
|
||||
@@ -314,15 +367,14 @@ function MyHand({ v, act, pending, players }: { v: OneCardView; act: (a: unknown
|
||||
setPick(null);
|
||||
setNote('');
|
||||
}, [turnKey]);
|
||||
useEffect(() => setDeclare(true), [v.turnNo]);
|
||||
|
||||
const byId = (id: string) => my.hand.find((c) => c.id === id);
|
||||
const sameRank = (a: Card, b: Card) => a.kind === 'std' && b.kind === 'std' && a.rank === b.rank;
|
||||
const leavesOne = my.hand.length - Math.max(1, sel.length) === 1;
|
||||
const leavesOne = sel.length > 0 && my.hand.length - sel.length === 1 && !v.options.autoDeclare;
|
||||
|
||||
// Playing never calls "원카드!" (§5.3): that is the round button's own press afterwards.
|
||||
const send = (ids: string[], extra: Record<string, unknown> = {}) => {
|
||||
const leaves = my.hand.length - ids.length === 1;
|
||||
act({ type: 'play', cardIds: ids, ...extra, ...(leaves && declare ? { declareOneCard: true } : {}) });
|
||||
act({ type: 'play', cardIds: ids, ...extra });
|
||||
setSel([]);
|
||||
setPick(null);
|
||||
};
|
||||
@@ -410,7 +462,8 @@ function MyHand({ v, act, pending, players }: { v: OneCardView; act: (a: unknown
|
||||
<button
|
||||
key={c.id}
|
||||
type="button"
|
||||
className="oc-card"
|
||||
className={`oc-card${arrived[c.id] !== undefined ? ' oc-in' : ''}`}
|
||||
style={arrived[c.id] !== undefined ? ({ '--anim-delay': `${arrived[c.id]}ms` } as CSSProperties) : undefined}
|
||||
data-legal={myTurn ? isLegal : undefined}
|
||||
data-id={c.id}
|
||||
aria-pressed={picked}
|
||||
@@ -441,9 +494,7 @@ function MyHand({ v, act, pending, players }: { v: OneCardView; act: (a: unknown
|
||||
canPlay={sel.length > 0 && legal.has(sel[0]!)}
|
||||
playLabel={sel.length > 1 ? `${sel.length}장 내기` : '내기'}
|
||||
onPlay={() => playIds(sel)}
|
||||
leavesOne={leavesOne && sel.length > 0}
|
||||
declare={declare}
|
||||
setDeclare={setDeclare}
|
||||
leavesOne={leavesOne}
|
||||
/>
|
||||
{pick && (
|
||||
<Sheet onClose={() => setPick(null)} label={pick.kind === 'suit' ? '무늬 고르기' : '색 고르기'}>
|
||||
@@ -479,13 +530,9 @@ function ActionBar(props: {
|
||||
playLabel: string;
|
||||
onPlay: () => void;
|
||||
leavesOne: boolean;
|
||||
declare: boolean;
|
||||
setDeclare: (b: boolean) => void;
|
||||
}) {
|
||||
const { v, act, pending, players, canPlay, playLabel, onPlay, leavesOne, declare, setDeclare } = props;
|
||||
const { v, act, pending, players, canPlay, playLabel, onPlay, leavesOne } = props;
|
||||
const my = v.my!;
|
||||
const w = v.oneCardWindow;
|
||||
const oneLabel = !w ? '원카드' : w.player === v.me ? '원카드 외치기' : `${nick(players, w.player)}님 잡기`;
|
||||
const myTurn = v.current === v.me && (v.phase === 'turn' || v.phase === 'afterDraw' || (v.phase === 'wild4Response' && my.legalCardIds.length > 0));
|
||||
return (
|
||||
<div className="oc-actions">
|
||||
@@ -505,27 +552,71 @@ function ActionBar(props: {
|
||||
</button>
|
||||
)}
|
||||
{myTurn && leavesOne && (
|
||||
<label className="row small" style={{ gap: 4, cursor: 'pointer', flex: '1 1 100%' }}>
|
||||
<input type="checkbox" checked={declare} onChange={(e) => setDeclare(e.target.checked)} style={{ width: 22, height: 22 }} />
|
||||
내면서 원카드 외치기
|
||||
</label>
|
||||
<span className="small" style={{ flex: '1 1 100%' }}>
|
||||
내고 나면 1장이 남아요. 낸 다음 [원카드!]를 따로 눌러요.
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="oc-onebtn"
|
||||
disabled={!my.canDeclare || pending}
|
||||
onClick={() => {
|
||||
haptic(40);
|
||||
act({ type: 'declareOneCard' });
|
||||
}}
|
||||
aria-label={my.canDeclare ? oneLabel : '원카드 (지금은 누를 수 없어요)'}
|
||||
>
|
||||
원카드!
|
||||
</button>
|
||||
<OneCardButton v={v} act={act} pending={pending} players={players} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* ms until others may catch the open window's owner (0 = now / not waiting). The owner may call at once; everyone
|
||||
* else waits out the protection time (`oneCardGrace`), counted on the server clock.
|
||||
*/
|
||||
function useCatchWait(v: OneCardView): number {
|
||||
const now = useServerNow(200);
|
||||
const w = v.oneCardWindow;
|
||||
if (!w || w.declared || w.player === v.me) return 0;
|
||||
// A little margin so a press right at the end is not refused for clock drift.
|
||||
return Math.max(0, w.catchFrom + 100 - now);
|
||||
}
|
||||
|
||||
/** The round "원카드!" button: call my own one card, or catch someone who forgot (after the protection time). */
|
||||
function OneCardButton({ v, act, pending, players }: { v: OneCardView; act: (a: unknown) => void; pending: boolean; players: Record<string, PublicUser> }) {
|
||||
const my = v.my!;
|
||||
const w = v.oneCardWindow;
|
||||
const wait = useCatchWait(v);
|
||||
const mine = !!w && w.player === v.me;
|
||||
const can = my.canDeclare && !pending && wait === 0;
|
||||
const secs = Math.ceil(wait / 1000);
|
||||
const label = !my.canDeclare || !w ? '원카드 (지금은 누를 수 없어요)' : mine ? '원카드 외치기' : wait > 0 ? `${nick(players, w.player)}님 잡기, ${secs}초 뒤에 누를 수 있어요` : `${nick(players, w.player)}님 잡기`;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`oc-onebtn${can && mine ? ' urgent' : ''}${my.canDeclare && wait > 0 ? ' wait' : ''}`}
|
||||
disabled={!can}
|
||||
onClick={() => {
|
||||
haptic(40);
|
||||
act({ type: 'declareOneCard' });
|
||||
}}
|
||||
aria-label={label}
|
||||
>
|
||||
{my.canDeclare && wait > 0 ? (
|
||||
<>
|
||||
잡기
|
||||
<br />
|
||||
{secs}초
|
||||
</>
|
||||
) : (
|
||||
'원카드!'
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** For players already out of the round: they may still catch. */
|
||||
function CatchButton({ v, act, pending, players }: { v: OneCardView; act: (a: unknown) => void; pending: boolean; players: Record<string, PublicUser> }) {
|
||||
const wait = useCatchWait(v);
|
||||
const who = v.oneCardWindow ? nick(players, v.oneCardWindow.player) : '';
|
||||
return (
|
||||
<button type="button" className="btn btn-secondary" disabled={pending || wait > 0} onClick={() => act({ type: 'declareOneCard' })}>
|
||||
{wait > 0 ? `${Math.ceil(wait / 1000)}초 뒤에 ${who}님 잡기` : `원카드! (${who}님 잡기)`}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- prompts
|
||||
|
||||
function Wild4Panel({ v, players, act, pending }: { v: OneCardView; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean }) {
|
||||
@@ -673,9 +764,12 @@ function OneCardBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
const opps = useSeatRows<HTMLUListElement>(others.length);
|
||||
const canDraw = !!v.my?.canDraw && !pending;
|
||||
const meSeat = v.seats.find((s) => s.id === me);
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const layerRef = useRef<HTMLDivElement>(null);
|
||||
const fx = useOneCardFx({ view: v, me, nick: (id) => nick(players, id) }, rootRef, layerRef);
|
||||
return (
|
||||
<div className="oc">
|
||||
<style>{CSS}</style>
|
||||
<div className="oc" ref={rootRef}>
|
||||
<style>{CSS + FX_CSS}</style>
|
||||
<ul className="oc-opps" aria-label="다른 사람" ref={opps.ref} style={opps.style}>
|
||||
{others.map((s) => (
|
||||
<SeatChip key={s.id} s={s} v={v} players={players} me={me} deadline={deadline} />
|
||||
@@ -685,36 +779,31 @@ function OneCardBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
v={v}
|
||||
players={players}
|
||||
canDraw={canDraw}
|
||||
fx={fx}
|
||||
onDraw={() => act({ type: 'draw' })}
|
||||
onDropCard={(id) => {
|
||||
if (v.my?.legalCardIds.includes(id)) {
|
||||
const c = v.my.hand.find((x) => x.id === id);
|
||||
if (c && !((c.kind === 'std' && c.rank === 7) || c.kind === 'wild' || c.kind === 'wild4')) {
|
||||
const leaves = v.my.hand.length === 2;
|
||||
act({ type: 'play', cardIds: [id], ...(leaves ? { declareOneCard: true } : {}) });
|
||||
}
|
||||
if (c && !((c.kind === 'std' && c.rank === 7) || c.kind === 'wild' || c.kind === 'wild4')) act({ type: 'play', cardIds: [id] });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Wild4Panel v={v} players={players} act={act} pending={pending} />
|
||||
<RevealPanel v={v} players={players} />
|
||||
<RoundPanel v={v} players={players} act={act} pending={pending} />
|
||||
{v.my && meSeat && meSeat.status === 'playing' && v.phase !== 'roundEnd' && v.phase !== 'finished' && <MyHand v={v} act={act} pending={pending} players={players} />}
|
||||
{v.my && meSeat && meSeat.status === 'playing' && v.phase !== 'roundEnd' && v.phase !== 'finished' && <MyHand v={v} act={act} pending={pending} players={players} arrived={fx.arrived} />}
|
||||
{meSeat && meSeat.status !== 'playing' && v.phase !== 'finished' && v.phase !== 'roundEnd' && (
|
||||
<div className="oc-panel">
|
||||
<strong>
|
||||
{meSeat.status === 'out' ? '카드를 모두 냈어요! 다른 사람의 게임을 지켜봐요.' : meSeat.status === 'bankrupt' ? '파산했어요. 남은 게임을 지켜봐요.' : '게임에서 나갔어요.'}
|
||||
</strong>
|
||||
{meSeat.status === 'out' && v.my?.canDeclare && (
|
||||
<button type="button" className="btn btn-secondary" disabled={pending} onClick={() => act({ type: 'declareOneCard' })}>
|
||||
원카드! ({v.oneCardWindow ? nick(players, v.oneCardWindow.player) : ''}님 잡기)
|
||||
</button>
|
||||
)}
|
||||
{meSeat.status === 'out' && v.my?.canDeclare && <CatchButton v={v} act={act} pending={pending} players={players} />}
|
||||
</div>
|
||||
)}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
<div className="oc-fxlayer" ref={layerRef} aria-hidden />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -884,7 +973,12 @@ function Options({ value: o, onChange }: OptionsProps<OneCardOptions>) {
|
||||
<Seg label="끝나는 때" value={o.endCondition} options={[['first-out', '1등이 나오면'], ['last-standing', '꼴찌가 정해질 때까지']]} onChange={(endCondition) => set({ endCondition })} />
|
||||
</Field>
|
||||
<Field label="한 턴 제한 시간">
|
||||
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[10, '10초'], [15, '15초'], [20, '20초'], [30, '30초'], [60, '60초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||
<Seg
|
||||
label="한 턴 제한 시간"
|
||||
value={o.turnSeconds === null ? 'none' : String(o.turnSeconds)}
|
||||
options={[['10', '10초'], ['15', '15초'], ['20', '20초'], ['30', '30초'], ['60', '60초'], ['none', '무제한']]}
|
||||
onChange={(k) => set({ turnSeconds: k === 'none' ? null : (Number(k) as 10 | 15 | 20 | 30 | 60) })}
|
||||
/>
|
||||
</Field>
|
||||
{!classic && (
|
||||
<Field label="색 바꾸기+4 내는 조건">
|
||||
@@ -953,7 +1047,13 @@ function Options({ value: o, onChange }: OptionsProps<OneCardOptions>) {
|
||||
<Field label="원카드를 못 외치고 잡히면">
|
||||
<Seg label="원카드 벌칙" value={o.oneCardPenalty} options={[['auto', classic ? '1장(기본)' : '2장(기본)'], [1, '1장'], [2, '2장'], [3, '3장']]} onChange={(oneCardPenalty) => set({ oneCardPenalty })} />
|
||||
</Field>
|
||||
<Field label="1장 남으면 자동으로 원카드 외치기">
|
||||
<Field label="원카드 잡기 전 보호 시간" help="1장 남은 사람만 [원카드!]를 누를 수 있는 시간이에요. 지나면 다른 사람이 잡을 수 있어요.">
|
||||
<Seg label="원카드 보호 시간" value={o.oneCardGrace} options={[[1, '1초'], [2, '2초(기본)'], [3, '3초']]} onChange={(oneCardGrace) => set({ oneCardGrace })} />
|
||||
</Field>
|
||||
<Field label="원카드를 외치면 다른 사람이 1장씩 먹기">
|
||||
<Seg label="원카드 보너스" value={o.oneCardBonus} options={onOff} onChange={(oneCardBonus) => set({ oneCardBonus })} />
|
||||
</Field>
|
||||
<Field label="1장 남으면 자동으로 원카드 외치기" help="초보·어린이용이에요. 켜면 아무도 잡을 수 없어요.">
|
||||
<Seg label="자동 원카드" value={o.autoDeclare} options={onOff} onChange={(autoDeclare) => set({ autoDeclare })} />
|
||||
</Field>
|
||||
<Field label="파산 장수">
|
||||
@@ -987,7 +1087,7 @@ function optionsSummary(o: OneCardOptions): string {
|
||||
if (o.unoTargetScore) parts.push(`${o.unoTargetScore}점까지`);
|
||||
}
|
||||
if (o.endCondition === 'last-standing') parts.push('꼴찌까지');
|
||||
parts.push(`${o.turnSeconds}초`);
|
||||
parts.push(o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`);
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
@@ -1049,6 +1149,8 @@ function Rules({ options }: { options?: OneCardOptions }) {
|
||||
multiPlay: false,
|
||||
oneCardPenalty: 'auto',
|
||||
autoDeclare: false,
|
||||
oneCardGrace: 2,
|
||||
oneCardBonus: false,
|
||||
bankruptLimit: 'auto',
|
||||
voluntaryDraw: true,
|
||||
playAfterDraw: 'auto',
|
||||
@@ -1084,8 +1186,11 @@ function Rules({ options }: { options?: OneCardOptions }) {
|
||||
)}
|
||||
<SpecialTable mode={full.mode} o={full} />
|
||||
<p>
|
||||
<strong>원카드</strong>: 카드를 내서 1장이 남으면 "원카드!" 버튼을 눌러요. 다른 사람이 먼저 누르면 {full.oneCardPenalty === 'auto' ? (classic ? 1 : 2) : full.oneCardPenalty}장을
|
||||
먹어요. 카드를 낼 때 "내면서 원카드 외치기"를 켜 두면 안전해요.
|
||||
<strong>원카드</strong>:{' '}
|
||||
{full.autoDeclare
|
||||
? '카드를 내서 1장이 남으면 저절로 원카드를 외쳐요.'
|
||||
: `카드를 내서 1장이 남으면, 낸 다음 동그란 [원카드!] 버튼을 따로 눌러 외쳐요(카드를 내면서 함께 외칠 수는 없어요). 처음 ${full.oneCardGrace}초는 나만 누를 수 있고, 그 뒤에는 다른 사람이 먼저 눌러 잡을 수 있어요. 잡히면 ${full.oneCardPenalty === 'auto' ? (classic ? 1 : 2) : full.oneCardPenalty}장을 먹어요.`}
|
||||
{full.oneCardBonus ? ' 먼저 외치면 다른 사람이 모두 1장씩 먹어요.' : ''}
|
||||
</p>
|
||||
{classic && (
|
||||
<p>
|
||||
@@ -1100,7 +1205,9 @@ function Rules({ options }: { options?: OneCardOptions }) {
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
시간 안에 고르지 않으면 카드를 내지 않고 자동으로 먹어요(공격받는 중이면 모인 장수만큼).{' '}
|
||||
{full.turnSeconds === null
|
||||
? '한 턴 시간 제한이 없어요(자리를 비운 사람만 잠깐 기다린 뒤 자동으로 먹어요). '
|
||||
: `${full.turnSeconds}초 안에 고르지 않으면 카드를 내지 않고 자동으로 먹어요(공격받는 중이면 모인 장수만큼). `}
|
||||
{full.bankruptLimit === 'none' || (full.bankruptLimit === 'auto' && !classic)
|
||||
? ''
|
||||
: `손에 ${full.bankruptLimit === 'auto' ? 20 : full.bankruptLimit}장 이상 쌓이면 파산해서 탈락해요.`}
|
||||
|
||||
@@ -68,6 +68,6 @@ export const quickStart: QuickCard[] = [
|
||||
),
|
||||
alt: '카드 1장과 노란 원카드 버튼',
|
||||
title: '1장 남으면 원카드!',
|
||||
text: '카드를 먼저 다 내면 이겨요. 1장 남으면 [원카드!]를 얼른 눌러요. 다른 사람이 먼저 누르면 벌로 카드를 먹어요.',
|
||||
text: '카드를 먼저 다 내면 이겨요. 1장 남으면 카드를 낸 다음 [원카드!]를 따로 얼른 눌러요. 조금 지나면 다른 사람이 먼저 눌러 잡을 수 있고, 잡히면 벌로 카드를 먹어요.',
|
||||
},
|
||||
];
|
||||
|
||||
@@ -30,12 +30,14 @@
|
||||
| `afterJoker` | (`classic`) 조커 다음에 낼 수 있는 카드 | `previous`(조커 밑 카드 기준) / `any`(아무 카드) | `previous` |
|
||||
| `multiPlay` | (`classic`) 같은 숫자 여러 장 동시 내기 | on / off | off |
|
||||
| `oneCardPenalty` | 원카드 선언을 못 해서 잡혔을 때 먹는 장수 | 1~3 (`uno-style` 원작 2) | `classic` 1, `uno-style` 2 |
|
||||
| `autoDeclare` | 1장이 되면 자동으로 선언(초보·어린이용) | on / off | off |
|
||||
| `autoDeclare` | 1장이 되면 자동으로 선언(초보·어린이용, 잡기 없음) | on / off | off |
|
||||
| `oneCardGrace` | 원카드 잡기 전 보호 시간: 창이 열린 뒤 이 시간 동안은 본인만 외칠 수 있다 | 1 / 2 / 3초 | 2초 |
|
||||
| `oneCardBonus` | 원카드를 먼저 외치면 다른 사람(진행 중인 사람 모두)이 1장씩 먹기(하우스 룰) | on / off | off |
|
||||
| `bankruptLimit` | 파산 장수(이 장수 이상이면 탈락) | 15 / 18 / 20 / 25 / 없음 | `classic` 20, `uno-style` 없음(원작에 없음) |
|
||||
| `voluntaryDraw` | 낼 카드가 있어도 일부러 1장 먹고 넘기기 허용 | on / off | on |
|
||||
| `playAfterDraw` | 먹은 카드가 낼 수 있는 카드면 바로 내기 허용 | on / off | `classic` off, `uno-style` on |
|
||||
| `endCondition` | 종료 시점 | `first-out`(1등이 나오면 종료) / `last-standing`(꼴찌가 정해질 때까지) | `first-out` |
|
||||
| `turnSeconds` | 턴 제한 시간 | 10 / 15 / 20 / 30 / 60 | 20 |
|
||||
| `turnSeconds` | 턴 제한 시간 | 10 / 15 / 20 / 30 / 60 / 무제한(`null`) | 20 |
|
||||
| `unoStacking` | (`uno-style`) +2/+4 받아치기(하우스 룰) | on / off | off |
|
||||
| `unoWild4Rule` | (`uno-style`) 색 바꾸기+4 사용 조건 | `strict`(현재 색이 손에 없을 때만, 서버가 막음) / `challenge`(원작: 아무 때나 내되 의심 신청 가능) / `free`(제한 없음) | `strict` |
|
||||
| `unoTargetScore` | (`uno-style`) 여러 판 점수제 목표 점수 | 없음(한 판) / 200 / 500 | 없음 |
|
||||
@@ -132,11 +134,14 @@
|
||||
- 기본 `joker`: 손에 조커 1장만 남으면 그 조커는 낼 수 없으므로 먹어야 한다(나무위키: "카드가 1장인 상태일 때는 조커를 내는 게 불가능하다").
|
||||
|
||||
### 5.3 원카드 선언
|
||||
- 카드를 내서 손패가 정확히 1장이 된 순간 그 플레이어에게 "선언 창"이 열린다. 이때 모든 참가자(관전자 제외)에게 "원카드!" 버튼이 활성화된다.
|
||||
- 카드를 내서 손패가 정확히 1장이 된 순간 그 플레이어에게 "선언 창"이 열린다(`openedAt` = 서버 시각).
|
||||
- **카드 내기와 원카드 외치기는 따로 하는 행동이다(2026-10-13).** 예전에는 `play`에 `declareOneCard: true`를 같이 보내 "내면서 외치기"가 됐는데, 그러면 잡힐 틈이 없어 너무 유리했다. 이제 `play`는 절대 외치지 않고(옛 클라이언트가 보낸 `declareOneCard` 필드는 스키마가 버린다), 낸 다음 `declareOneCard` 액션을 따로 보내야 한다. 예외는 `autoDeclare = on`뿐이다.
|
||||
- 보호 시간(`oneCardGrace`, 기본 2초): 창이 열리고 이 시간 동안은 본인만 외칠 수 있다. 다른 사람의 잡기는 "아직 잡을 수 없어요"로 거부된다(서버 시각 `ctx.now` 기준, 테스트처럼 시각이 없으면 검사하지 않음). 보호 시간이 지나면 참가자 누구나(관전자·탈락자 제외) 버튼을 눌러 잡을 수 있다. view의 `oneCardWindow.catchFrom`이 잡기가 열리는 시각이다.
|
||||
- 서버 도착 순서로 판정한다.
|
||||
- 1장 남은 본인이 먼저 누르면 안전하다(`declared`).
|
||||
- 1장 남은 본인이 먼저 누르면 안전하다(`declared`). `oneCardBonus = on`이면 이때 진행 중인 다른 사람이 차례 순서대로 1장씩 먹는다(로그 `why: 'bonus'`).
|
||||
- 다른 플레이어가 먼저 누르면 본인이 `oneCardPenalty`장을 먹는다(잡힘). 먹은 뒤에는 손패가 2장 이상이라 창이 닫힌다.
|
||||
- 카드를 내는 액션에 `declareOneCard: true`를 같이 보낼 수 있다(UI에서 "내면서 원카드 외치기"). 이 경우 창이 열리는 순간 바로 선언된 것으로 처리한다.
|
||||
- 게임은 창의 주인이 외치기를 기다린다(`activePlayers`에 주인이 들어감, 시간 제한은 없음). 잡기는 누구나 할 수 있지만 기다리지는 않는다.
|
||||
- 컴퓨터도 따로 외친다. 사람처럼 바로 외치지 않고 반응 시간이 있다(`bot.ts`의 `oneCardReaction`): 어려움 0.5~1.5초(가끔 1.8~3.2초), 보통 0.9~2.8초(가끔 3~5초), 쉬움 1.4~4초(4번에 1번은 5~9초). 남이 깜빡한 것을 알아채는 확률은 어려움 90%, 보통 70%, 쉬움 45%이고, 알아채면 보호 시간이 끝난 뒤 0.2~4초 사이에 잡는다. 같은 창이면 몇 번 물어도 같은 답(창 번호로 정한 값)이다. 서버의 봇 드라이버가 이 시각에 맞춰 차례와 상관없이 누른다(`BOT_REACTIONS`).
|
||||
- 창이 닫히는 때: 본인 선언, 잡힘, 본인 손패 수가 1이 아니게 됨(공격 등으로 카드를 먹음), 또는 그 사람의 다음 턴이 시작됨. 다음 턴까지 아무도 잡지 못했으면 그대로 마지막 카드를 내고 나갈 수 있다.
|
||||
- 창이 열려 있는 동안에도 게임은 멈추지 않는다. 다음 사람은 바로 자기 턴을 진행할 수 있다.
|
||||
- `autoDeclare = on`이면 1장이 되는 순간 자동으로 선언된다.
|
||||
@@ -245,10 +250,10 @@ interface OneCardState {
|
||||
### 8.2 액션
|
||||
| type | payload | 누가 / 언제 | 검증 조건 |
|
||||
|---|---|---|---|
|
||||
| `play` | `{ cardIds: string[]; chooseSuit?: Suit; chooseColor?: Color; declareOneCard?: boolean }` | `current`, phase=`turn` 또는 `afterDraw` | 카드가 모두 자기 손에 있음. `multiPlay` off면 1장, on이면 숫자가 모두 같음. 공격 중이면 받아치기표나 3 방어 조건, 아니면 5.2 B 조건. 7이면 `chooseSuit` 필수, 색 바꾸기류면 `chooseColor` 필수. `lastCardRule` 위반 아님. `afterDraw`면 방금 뽑은 카드 1장만. `uno-style`의 `strict`이면 +4 조건 |
|
||||
| `play` | `{ cardIds: string[]; chooseSuit?: Suit; chooseColor?: Color }` (외치기는 따로) | `current`, phase=`turn` 또는 `afterDraw` | 카드가 모두 자기 손에 있음. `multiPlay` off면 1장, on이면 숫자가 모두 같음. 공격 중이면 받아치기표나 3 방어 조건, 아니면 5.2 B 조건. 7이면 `chooseSuit` 필수, 색 바꾸기류면 `chooseColor` 필수. `lastCardRule` 위반 아님. `afterDraw`면 방금 뽑은 카드 1장만. `uno-style`의 `strict`이면 +4 조건 |
|
||||
| `draw` | `{}` | `current`, phase=`turn` | 공격 중이면 항상 가능(누적량만큼 먹음). 아니면 `voluntaryDraw` on이거나 낼 카드가 없을 때 |
|
||||
| `pass` | `{}` | `current`, phase=`afterDraw` | 뽑은 카드를 내지 않고 턴 종료 |
|
||||
| `declareOneCard` | `{}` | 참가자 누구나(관전자·탈락자 제외), `oneCardWindow` 열림 | 창이 열려 있고 아직 판정 전. 본인이면 선언, 타인이면 잡기 |
|
||||
| `declareOneCard` | `{}` | 참가자 누구나(관전자·탈락자 제외), `oneCardWindow` 열림 | 창이 열려 있고 아직 판정 전. 본인이면 선언(언제든), 타인이면 잡기(보호 시간 `oneCardGrace`가 지난 뒤) |
|
||||
| `challengeWild4` | `{}` | phase=`wild4Response`의 `target` | `unoWild4Rule = challenge` |
|
||||
| `acceptWild4` | `{}` | phase=`wild4Response`의 `target` | 같음 |
|
||||
|
||||
@@ -276,6 +281,7 @@ interface OneCardState {
|
||||
|
||||
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
|
||||
- `deadline`: `turnStartedAt + turnSeconds*1000`. `wild4Response`는 10초. 원카드 창에는 마감이 없다.
|
||||
- `turnSeconds = null`(무제한)이면 턴과 `wild4Response`에 마감이 없다. 자리 비움(5초)과 판 사이 쉬는 시간은 그대로다.
|
||||
- `onTimeout(state, player)`
|
||||
- 공격을 받는 중이면 `draw`(누적량 먹기). 자동 받아치기는 하지 않는다.
|
||||
- 일반 턴이면 `draw`. 자동으로 카드를 내지 않는 쪽이 공정성 시비가 적다.
|
||||
@@ -310,8 +316,15 @@ interface GameResult {
|
||||
- 낼 수 없는 카드는 회색 처리하고, 낼 수 있는 카드에 테두리를 표시한다.
|
||||
- 7이나 색 바꾸기를 내면 큰 무늬/색 버튼 4개가 뜬다.
|
||||
- 공격을 받을 때는 "N장 먹기" 버튼과 받아칠 수 있는 카드 하이라이트를 같이 보여 준다.
|
||||
- 원카드 버튼: 화면 오른쪽 아래에 큰 원형 버튼이 있고, 누군가 1장이 되면 흔들리며 활성화된다. 내가 1장을 남기는 카드를 고르면 "원카드 외치며 내기"가 기본 선택이다.
|
||||
- 애니메이션: 카드 날아가기, 공격 누적 숫자 커지기, 방향 전환 화살표 회전, 파산 시 카드 흩어짐. 모두 300ms 이하이고, "애니메이션 줄이기" 설정을 따른다.
|
||||
- 원카드 버튼: 손패 아래 큰 원형 버튼. 내가 1장이 되면 흔들리고 계속 두근거리며 눌러 달라고 한다. 남이 1장이 되면 보호 시간 동안 "잡기 N초"로 세다가 0이 되면 켜진다. 1장을 남기는 카드를 고르면 "낸 다음 [원카드!]를 따로 눌러요" 안내가 뜬다(내면서 외치기는 없다).
|
||||
- 소리·움직임(`apps/web/src/games/one-card/fx.tsx`): 모두 view의 새 로그(`seq`)에 반응하므로 상대·컴퓨터가 한 일에도 똑같이 나오고, 같은 변화로 두 번 울리지 않는다.
|
||||
- 처음 나눠 주기·새 판: 섞는 소리와 함께 더미에서 각 자리로 카드 뒷면이 날아가고, 내 카드가 한 장씩 손에 내려앉는다.
|
||||
- 카드 먹기: 먹는 장수만큼(최대 12장) 카드 뒷면이 더미에서 먹는 사람 손/자리로 한 장씩 날아가고, 한 장마다 "착" 소리가 점점 높아진다. 4장 이상이나 원카드 벌칙이면 판이 흔들리며 빨갛게 번쩍이고, "+N장" 큰 글자가 뜬다.
|
||||
- 공격 누적: "+N장!" 배지가 한 장씩 세어 올라가며(틱 소리) 커지고, 누적이 클수록 글자가 커지고 불타듯 깜빡인다. 조커·큰 공격은 큰 효과음과 글자.
|
||||
- 카드 내기: 낸 사람 자리에서 바닥으로 날아온다. 7·색 바꾸기는 고른 무늬/색 글자와 색 번쩍임, 방향 바꾸기는 화살표 회전, 건너뛰기·3 막기·K 한 번 더·원카드!·잡았다!·파산·N등은 큰 글자와 각각의 소리.
|
||||
- 더미 다시 섞기: 더미가 흔들리며 섞는 소리.
|
||||
- 이기면/지면 결과 창에서 공통 승리·패배 소리(방 화면이 낸다).
|
||||
- 모든 움직임은 0.3~0.7초이고 `pointer-events: none`이라 클릭을 막지 않는다. "동작 줄이기"면 날아가는 카드와 흔들림이 꺼진다.
|
||||
- 초보자 도움말
|
||||
- "규칙 보기"에 특수 카드 표를 그림으로 넣는다.
|
||||
- 처음 몇 판은 "힌트" 토글로 낼 수 있는 카드 이유를 보여 준다(예: "♥ 무늬가 같아요").
|
||||
@@ -328,7 +341,9 @@ interface GameResult {
|
||||
- [ ] J를 2인에서 내면 낸 사람이 다시 턴을 한다. Q를 2인에서 내면 기본값에서 상대 턴이다.
|
||||
- [ ] K `extra-turn`: 추가 턴에 낼 카드가 없으면 1장을 먹는다. K가 마지막 카드면 바로 나간다.
|
||||
- [ ] `lastCardRule = joker`: 손패가 [조커, ♥5]인 상태에서 ♥5를 내면 조커 1장이 남는다. 다음 턴에 조커를 내려 하면 "마지막 카드로 조커는 낼 수 없어요"로 거부된다.
|
||||
- [ ] 원카드: A가 ♥5를 내서 1장이 되었을 때 B의 `declareOneCard`가 먼저 도착하면 A가 1장을 먹는다. A가 먼저 도착하면 B의 요청은 무시된다. `play`에 `declareOneCard: true`를 같이 보내면 잡히지 않는다.
|
||||
- [ ] 원카드: A가 ♥5를 내서 1장이 되었을 때 보호 시간(2초)이 지난 뒤 B의 `declareOneCard`가 먼저 도착하면 A가 1장을 먹는다. 보호 시간 안의 B 요청은 거부된다. A가 먼저 도착하면 B의 요청은 무시된다. `play`에 `declareOneCard: true`를 같이 보내도 외친 것이 아니다(필드가 버려짐).
|
||||
- [ ] `oneCardBonus`: A가 먼저 외치면 B·C가 1장씩 먹는다. `turnSeconds = null`이면 턴 마감이 없다.
|
||||
- [ ] 컴퓨터의 원카드: 자기 1장은 반응 시간 뒤에 따로 외치고, 남의 깜빡을 알아채면 보호 시간 뒤에 잡는다(방 테스트 `bots.room.test.ts`).
|
||||
- [ ] 파산: 손패 15장에서 공격 5장을 먹어 20장이 되면 즉시 파산한다. 그 카드는 드로우 더미 아래로 가고 턴 순서에서 빠진다. 2인 게임이면 상대가 바로 1등이다.
|
||||
- [ ] 드로우 더미 0장에서 7장을 먹을 때 버린 더미(맨 위 제외)가 섞여 보충된다. 그래도 부족하면 있는 만큼만 먹고 오류 없이 진행된다.
|
||||
- [ ] `uno-style` `strict`: 현재 색이 빨강이고 손에 빨강 3이 있으면 색 바꾸기+4가 거부된다. 빨강이 없고 파랑 +2만 있으면 허용된다.
|
||||
|
||||
@@ -1225,12 +1225,18 @@ const PLANS: Record<string, Plan> = {
|
||||
'one-card': {
|
||||
// 3 players, default 원카드: whoever has the turn plays a highlighted card (tap to lift, tap again to play,
|
||||
// pick a suit for 7) or draws; the 원카드 button is pressed whenever it lights up. 60 turns or until the game ends.
|
||||
// Checks on the way: playing down to one card never calls by itself (the separate round button is still lit for
|
||||
// the owner, the others count down "잡기 N초" first), cards fly from the deck when someone draws.
|
||||
players: 3,
|
||||
drive: async (pages) => {
|
||||
const statusOf = (p: Page) => p.locator('.turn-status').innerText().catch(() => '');
|
||||
const handCount = (p: Page) => p.locator('.oc-hand button.oc-card').count();
|
||||
const shot = (p: Page, name: string) => p.screenshot({ path: join(SHOTS, `one-card-${name}-${tag(p)}.png`), fullPage: tag(p) === 'phone' });
|
||||
let turns = 0;
|
||||
let plays = 0;
|
||||
let draws = 0;
|
||||
let flown = 0;
|
||||
let separateCall = 0;
|
||||
let finished = false;
|
||||
for (let t = 0; t < 600 && turns < 60; t++) {
|
||||
if (await pages[0]!.getByRole('dialog', { name: '게임 결과' }).count()) {
|
||||
@@ -1247,16 +1253,43 @@ const PLANS: Record<string, Plan> = {
|
||||
const card = p.locator('button.oc-card[data-legal="true"]').first();
|
||||
if (await accept.count()) await accept.click();
|
||||
else if (await card.count()) {
|
||||
const leavesOne = (await handCount(p)) === 2;
|
||||
await card.click();
|
||||
if (leavesOne && !separateCall) {
|
||||
await p.getByText('낸 다음 [원카드!]를 따로 눌러요').waitFor({ timeout: 2000 });
|
||||
await shot(p, 'before-last');
|
||||
}
|
||||
await card.click();
|
||||
const pick = p.locator('.oc-pick button').first();
|
||||
if (await pick.waitFor({ timeout: 400 }).then(() => true, () => false)) await pick.click();
|
||||
plays++;
|
||||
if (leavesOne && !separateCall && (await p.locator('.oc-onebtn.urgent').waitFor({ timeout: 3000 }).then(() => true, () => false))) {
|
||||
// Not called by the play: the owner's button pulses, another player waits out the protection time.
|
||||
const other = pages.find((q) => q !== p)!;
|
||||
await other.locator('.oc-onebtn.wait').waitFor({ timeout: 2000 });
|
||||
if (!(await other.locator('.oc-onebtn').isDisabled())) throw new Error('catch button lit during the protection time');
|
||||
await shot(p, 'call');
|
||||
await shot(other, 'catch-wait');
|
||||
await p.emulateMedia({ colorScheme: 'dark' });
|
||||
await p.waitForTimeout(300);
|
||||
await shot(p, 'call-dark');
|
||||
await p.emulateMedia({ colorScheme: 'light' });
|
||||
separateCall++;
|
||||
}
|
||||
} else {
|
||||
const pass = p.getByRole('button', { name: '넘기기' });
|
||||
if (await pass.count()) await pass.click();
|
||||
else await p.getByRole('button', { name: /장 먹기$/ }).first().click();
|
||||
draws++;
|
||||
// Cards fly from the deck to whoever draws, on every screen.
|
||||
const watcher = pages.find((q) => q !== p)!;
|
||||
if (flown < 2 && (await watcher.locator('.oc-fly').first().waitFor({ timeout: 1500 }).then(() => true, () => false))) {
|
||||
flown++;
|
||||
if (flown === 1) {
|
||||
await shot(watcher, 'draw-fly');
|
||||
await shot(p, 'draw-fly');
|
||||
}
|
||||
}
|
||||
}
|
||||
await p.waitForFunction((s) => document.querySelector('.turn-status')?.textContent?.trim() !== s, before.trim(), { timeout: 5000 }).catch(() => {});
|
||||
turns++;
|
||||
@@ -1267,7 +1300,8 @@ const PLANS: Record<string, Plan> = {
|
||||
}
|
||||
if (!finished && turns < 30) throw new Error(`only ${turns} turns were played`);
|
||||
if (finished) await pages[0]!.screenshot({ path: join(SHOTS, 'one-card-3-result-pc.png') });
|
||||
console.log(` one-card: ${turns} turns (${plays} plays, ${draws} draws)${finished ? ', game finished' : ''}`);
|
||||
if (draws > 0 && !flown) throw new Error('no flying cards seen when someone drew');
|
||||
console.log(` one-card: ${turns} turns (${plays} plays, ${draws} draws, separate 원카드 checked ${separateCall}×, draw flights seen ${flown}×)${finished ? ', game finished' : ''}`);
|
||||
},
|
||||
},
|
||||
uno: {
|
||||
|
||||
Reference in New Issue
Block a user