병합: wt2/one-card
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
/** Computer players in rooms (docs/06-lobby-rooms.md §12): seating rules, practice rooms, driving, records, restore. */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { BOT_STRATEGIES, LIVE_BOT_STRATEGIES } from '@bg/games/bots';
|
||||
import { BOT_STRATEGIES, LIVE_BOT_STRATEGIES, botReactionAt } from '@bg/games/bots';
|
||||
import { classicDeck, type OneCardState } from '@bg/games/one-card';
|
||||
import { BOT_GAMES, ClientMessage, botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { botPace, defaultBotDelay, type BotDelayInput } from './bots';
|
||||
@@ -338,6 +339,63 @@ describe('playing with bots', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('원카드: computers call and catch on their own reaction clock', () => {
|
||||
test('a computer that played down to one card calls at its reaction time; a person can catch only after 2 s', () => {
|
||||
const h = harness(undefined, undefined, (input) => defaultBotDelay(input, () => 0.5));
|
||||
const room = h.manager.createPractice('A', 'one-card') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bot = bots(room)[0]!;
|
||||
// Rig: the computer's turn with [♥9, ♣3] on ♥5; the person is next.
|
||||
const s = room.game!.state as OneCardState;
|
||||
const deck = classicDeck(1);
|
||||
const take = (ids: string[]) => ids.map((id) => deck.find((c) => c.id === id)!);
|
||||
s.hands = { A: take(['S4', 'S6', 'D8']), [bot]: take(['H9', 'C3']) };
|
||||
s.discard = take(['H5']);
|
||||
s.drawPile = deck.filter((c) => !['S4', 'S6', 'D8', 'H9', 'C3', 'H5'].includes(c.id));
|
||||
s.current = bot;
|
||||
s.phase = { kind: 'turn' };
|
||||
s.pendingAttack = 0;
|
||||
s.declaredSuit = null;
|
||||
s.oneCardWindow = null;
|
||||
room.bots.cancel();
|
||||
room.scheduleTimer();
|
||||
for (let k = 0; k < 5 && !(room.game!.state as OneCardState).oneCardWindow; k++) {
|
||||
h.clock.advance(Math.max(0, (room.bots.dueAt ?? h.clock.now()) - h.clock.now()));
|
||||
room.bots.fire();
|
||||
}
|
||||
let st = room.game!.state as OneCardState;
|
||||
expect(st.oneCardWindow).toMatchObject({ player: bot, declared: false });
|
||||
expect(st.current).toBe('A');
|
||||
const opened = st.oneCardWindow!.openedAt!;
|
||||
// Planned exactly at its reaction time (not squeezed by the turn clock, no thinking chat).
|
||||
const at = botReactionAt(room.def, st, bot, room.profile(bot).level) as number;
|
||||
expect(at).toBeGreaterThanOrEqual(opened + 500);
|
||||
expect(room.bots.dueAt).toBe(at);
|
||||
const rejects = () => a.msgs.filter((m) => m.t === 'reject').length;
|
||||
const before = rejects();
|
||||
room.act('A', 101, { type: 'declareOneCard' });
|
||||
expect(rejects()).toBe(before + 1);
|
||||
if (at > opened + 2000) {
|
||||
// Slow this time: the person catches it first and the planned call is dropped.
|
||||
h.clock.advance(opened + 2000 - h.clock.now());
|
||||
room.act('A', 102, { type: 'declareOneCard' });
|
||||
st = room.game!.state as OneCardState;
|
||||
expect(st.oneCardWindow).toBeNull();
|
||||
expect(st.hands[bot]).toHaveLength(2);
|
||||
expect(room.bots.dueAt).toBeNull();
|
||||
} else {
|
||||
h.clock.advance(at - h.clock.now());
|
||||
room.bots.fire();
|
||||
st = room.game!.state as OneCardState;
|
||||
expect(st.oneCardWindow).toMatchObject({ player: bot, declared: true });
|
||||
expect(st.hands[bot]).toHaveLength(1);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('practice rooms close once nobody is there', () => {
|
||||
function finishedPractice() {
|
||||
const h = harness();
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
import { secureRandom, type AnyGameDefinition } from '@bg/engine';
|
||||
import { isBotId } from '@bg/shared';
|
||||
import { LIVE_BOT_STRATEGIES, botCandidates, botPace, botPersona, decideBotAction, idLevel, type LiveBotStrategy } from '@bg/games/bots';
|
||||
import { LIVE_BOT_STRATEGIES, botCandidates, botPace, botPersona, botReactionAt, decideBotAction, idLevel, type LiveBotStrategy } from '@bg/games/bots';
|
||||
|
||||
import type { BotBrain } from '../ai/brain';
|
||||
|
||||
@@ -39,6 +39,8 @@ export interface BotDelayInput {
|
||||
bot: string;
|
||||
/** The same bot just acted and is still on (e.g. yacht keep → roll): it already knows what it wants. */
|
||||
followUp: boolean;
|
||||
/** An out-of-turn reaction the game timed itself (원카드 외치기·잡기, `botReactionAt`): wait exactly this long. */
|
||||
reactMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -49,6 +51,7 @@ export interface BotDelayInput {
|
||||
*/
|
||||
export function defaultBotDelay(input: BotDelayInput, random: () => number = secureRandom): number {
|
||||
const { choices, withPeople, bot, followUp } = input;
|
||||
if (input.reactMs !== undefined) return Math.max(0, Math.round(input.reactMs));
|
||||
let ms = choices <= 1 ? 700 + random() * 600 : 1300 + 300 * Math.min(Math.log2(choices), 4) + random() * 1400;
|
||||
if (choices > 1 && !followUp && random() < 0.12) ms += 1000 + random() * 2000;
|
||||
ms *= botPace(bot);
|
||||
@@ -68,6 +71,8 @@ export class BotDriver {
|
||||
dueAt: number | null = null;
|
||||
/** Bot the planned action is for. */
|
||||
private planned: string | null = null;
|
||||
/** The planned action is that bot's out-of-turn reaction due at this time (not its normal move). */
|
||||
private plannedReact: number | null = null;
|
||||
/** Bot whose action is being played right now: if it is still on afterwards, its next move is a follow-up. */
|
||||
private acting: string | null = null;
|
||||
/** Live games (마피아): when each computer looks at the game again, and its notes for the current game. */
|
||||
@@ -87,26 +92,65 @@ export class BotDriver {
|
||||
/** Plans the next bot action if the game is waiting on a bot. Keeps an already planned one (the bot is "thinking"). */
|
||||
schedule(): void {
|
||||
if (this.liveStrategy()) return this.scheduleLive();
|
||||
if (this.dueAt !== null || this.busy) return;
|
||||
if (this.busy) return;
|
||||
if (this.dueAt !== null) {
|
||||
// A planned reaction the moment has passed for (someone called first): plan again; anything else stays planned.
|
||||
if (this.plannedReact === null || this.reactionDue()?.bot === this.planned) return;
|
||||
if (this.timer) clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
this.dueAt = null;
|
||||
this.planned = null;
|
||||
this.plannedReact = null;
|
||||
}
|
||||
const next = this.next();
|
||||
if (!next) return;
|
||||
// People can see it think: "생각 중…" until it moves.
|
||||
if (this.room.brain?.enabled()) this.room.brain.thinking(next.bot, true);
|
||||
const react = this.reactionDue();
|
||||
if (!next && !react) return;
|
||||
const now = this.room.now();
|
||||
let ms = this.delay({ choices: next.choices, withPeople: next.withPeople, bot: next.bot, followUp: next.bot === this.acting });
|
||||
const deadline = this.room.deadline?.() ?? null;
|
||||
if (deadline !== null) ms = Math.min(ms, Math.max(0, (deadline - now) * BOT_DEADLINE_SHARE));
|
||||
let ms = Infinity;
|
||||
if (next) {
|
||||
ms = this.delay({ choices: next.choices, withPeople: next.withPeople, bot: next.bot, followUp: next.bot === this.acting });
|
||||
const deadline = this.room.deadline?.() ?? null;
|
||||
if (deadline !== null) ms = Math.min(ms, Math.max(0, (deadline - now) * BOT_DEADLINE_SHARE));
|
||||
}
|
||||
// An out-of-turn reaction (원카드!) comes first when it is due earlier; it is not squeezed by the turn clock, so a
|
||||
// slow computer can really be late.
|
||||
if (react) {
|
||||
const rms = this.delay({ choices: 1, withPeople: true, bot: react.bot, followUp: false, reactMs: react.at - now });
|
||||
if (rms <= ms) {
|
||||
this.dueAt = now + rms;
|
||||
this.planned = react.bot;
|
||||
this.plannedReact = react.at;
|
||||
return this.arm();
|
||||
}
|
||||
}
|
||||
// People can see it think: "생각 중…" until it moves.
|
||||
if (this.room.brain?.enabled()) this.room.brain.thinking(next!.bot, true);
|
||||
this.dueAt = now + ms;
|
||||
this.planned = next.bot;
|
||||
this.planned = next!.bot;
|
||||
this.plannedReact = null;
|
||||
this.arm();
|
||||
}
|
||||
|
||||
/** The earliest out-of-turn reaction of a computer that may act now (games with `BOT_REACTIONS`). */
|
||||
private reactionDue(): { bot: string; at: number } | null {
|
||||
const g = this.room.game;
|
||||
if (!g || g.finished || this.room.status !== 'playing') return null;
|
||||
let best: { bot: string; at: number } | null = null;
|
||||
for (const p of g.players) {
|
||||
if (!isBotId(p)) continue;
|
||||
const at = botReactionAt(this.room.def, g.state, p, this.room.profile?.(p).level ?? idLevel(p));
|
||||
if (typeof at === 'number' && (!best || at < best.at)) best = { bot: p, at };
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
cancel(): void {
|
||||
if (this.timer) clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
if (this.planned) this.room.brain?.thinking(this.planned, false);
|
||||
this.dueAt = null;
|
||||
this.planned = null;
|
||||
this.plannedReact = null;
|
||||
this.liveDue.clear();
|
||||
}
|
||||
|
||||
@@ -219,8 +263,11 @@ export class BotDriver {
|
||||
const active = def.activePlayers(g.state);
|
||||
const waiting = new Set([...active, ...(def.timeoutPlayers?.(g.state) ?? [])]);
|
||||
const withPeople = active.some((p) => !isBotId(p));
|
||||
const timed = new Set(def.timeoutPlayers?.(g.state) ?? active);
|
||||
for (const p of g.players) {
|
||||
if (!isBotId(p) || !waiting.has(p)) continue;
|
||||
// Only there to react out of turn (원카드!): `reactionDue` times that, not the thinking time.
|
||||
if (!timed.has(p) && botReactionAt(def, g.state, p, this.room.profile?.(p).level ?? idLevel(p)) !== null) continue;
|
||||
const choices = botCandidates(def, g.state, p).length;
|
||||
if (choices > 0) return { bot: p, choices, withPeople };
|
||||
}
|
||||
@@ -239,13 +286,16 @@ export class BotDriver {
|
||||
return this.fireLive(live);
|
||||
}
|
||||
const planned = this.planned;
|
||||
const wasReact = this.plannedReact !== null;
|
||||
this.dueAt = null;
|
||||
this.planned = null;
|
||||
const next = this.next();
|
||||
this.plannedReact = null;
|
||||
const react = wasReact ? this.reactionDue() : null;
|
||||
const next = wasReact ? (react && react.bot === planned ? { bot: react.bot } : null) : this.next();
|
||||
const g = this.room.game;
|
||||
if (!next || !g) return;
|
||||
// Another bot's turn came up meanwhile: give it its own thinking time.
|
||||
if (next.bot !== planned) return this.schedule();
|
||||
if (!g) return;
|
||||
// Another bot's turn came up meanwhile (or the reaction is moot): give it its own thinking time.
|
||||
if (!next || next.bot !== planned) return this.schedule();
|
||||
const def = this.room.def;
|
||||
const t0 = performance.now();
|
||||
let action: unknown;
|
||||
@@ -258,7 +308,8 @@ export class BotDriver {
|
||||
const ms = performance.now() - t0;
|
||||
if (ms > BOT_SLOW_MS) this.room.log?.('warn', 'slow bot move', { game: def.id, ms: Math.round(ms) });
|
||||
const brain = this.room.brain;
|
||||
if (brain && action != null && brain.enabled()) {
|
||||
// A reaction (원카드!) is a reflex: no chat before it.
|
||||
if (brain && action != null && brain.enabled() && !wasReact) {
|
||||
// Like a person: maybe type something first (the model writes it; "입력 중…" while typing), then move.
|
||||
const bot = next.bot;
|
||||
this.busy = bot;
|
||||
|
||||
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: {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
import { secureRandom, type AnyGameDefinition, type PlayerId } from '@bg/engine';
|
||||
import type { BotLevel } from './persona';
|
||||
import type { BotStrategy, LiveBotStrategy } from './types';
|
||||
import type { BotReaction, BotStrategy, LiveBotStrategy } from './types';
|
||||
import { pick, playable, randomPolicy } from './policy';
|
||||
import { omokBot } from '../omok/bot';
|
||||
import { othelloBot } from '../othello/bot';
|
||||
@@ -16,7 +16,7 @@ import { seotdaBot } from '../seotda/bot';
|
||||
import { pokerBot } from '../poker/bot';
|
||||
import { yachtBot } from '../yacht/bot';
|
||||
import { yutBot } from '../yut/bot';
|
||||
import { oneCardBot } from '../one-card/bot';
|
||||
import { oneCardBot, oneCardReaction } from '../one-card/bot';
|
||||
import { rummikubBot } from '../rummikub/bot';
|
||||
import { gostopBot } from '../gostop/bot';
|
||||
import { bangBot } from '../bang/bot';
|
||||
@@ -38,7 +38,7 @@ import { unoBot } from '../uno/bot';
|
||||
import { liarBot } from '../liar/bot';
|
||||
import { magicalAthleteBot } from '../magical-athlete/bot';
|
||||
|
||||
export type { BotInput, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
|
||||
export type { BotInput, BotReaction, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
|
||||
export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona';
|
||||
export { botPlay } from './policy';
|
||||
|
||||
@@ -73,6 +73,22 @@ export const BOT_STRATEGIES: Record<string, BotStrategy> = {
|
||||
'magical-athlete': magicalAthleteBot,
|
||||
};
|
||||
|
||||
/** Games whose computers also react out of turn on their own clock (원카드 외치기·잡기). */
|
||||
export const BOT_REACTIONS: Record<string, BotReaction> = {
|
||||
'one-card': oneCardReaction,
|
||||
};
|
||||
|
||||
/** When `me` reacts out of turn (server time), 'ignore', or null (nothing to react to / the game has no reactions). */
|
||||
export function botReactionAt(def: AnyGameDefinition, state: unknown, me: PlayerId, level?: BotLevel): number | 'ignore' | null {
|
||||
const react = BOT_REACTIONS[def.id];
|
||||
if (!react) return null;
|
||||
try {
|
||||
return react({ me, view: def.view(state, me), level });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The bot's legal actions as the game lists them (validated lazily: only the chosen one, see below). */
|
||||
export function botCandidates(def: AnyGameDefinition, state: unknown, me: PlayerId): unknown[] {
|
||||
return def.legalActions ? def.legalActions(state, me) : [];
|
||||
|
||||
@@ -56,3 +56,10 @@ export interface LiveBotDecision<A = any> {
|
||||
}
|
||||
|
||||
export type LiveBotStrategy<V = any, A = any> = (input: LiveBotInput<V>) => LiveBotDecision<A>;
|
||||
|
||||
/**
|
||||
* Out-of-turn reactions (원카드 외치기·잡기): when (server time, ms) this computer reacts to what is on its screen now,
|
||||
* 'ignore' when it doesn't notice (left alone unless the game waits on it), or null when there is nothing to react to
|
||||
* (normal thinking time). Must give the same answer every time it is asked about the same moment.
|
||||
*/
|
||||
export type BotReaction<V = any> = (input: { me: PlayerId; view: V; level?: import('./persona').BotLevel }) => number | 'ignore' | null;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, seedN } from '@bg/engine';
|
||||
import { decideBotAction } from '../bots/index';
|
||||
import { botPlayout } from '../bots/playout';
|
||||
import { callDelayMs, catchDelayMs, noticesMissedCall, oneCardReaction } from './bot';
|
||||
import { classicDeck, oneCard, unoDeck, type Card, type OneCardOptions, type OneCardState } from './index';
|
||||
|
||||
const ALL: Card[] = [...classicDeck(2), ...unoDeck()];
|
||||
@@ -25,7 +26,7 @@ function rig(s: OneCardState, hands: Record<string, string[]>, discard: string[]
|
||||
return s;
|
||||
}
|
||||
|
||||
const decide = (s: OneCardState, p = 'A') => decideBotAction(oneCard, s, p, { now: 0, random: () => 0.5 }) as Record<string, unknown>;
|
||||
const decide = (s: OneCardState, p = 'A', now = 0, level?: number) => decideBotAction(oneCard, s, p, { now, random: () => 0.5, level }) as Record<string, unknown>;
|
||||
|
||||
describe('one-card bot', () => {
|
||||
test('counters an attack instead of drawing', () => {
|
||||
@@ -38,9 +39,12 @@ describe('one-card bot', () => {
|
||||
expect(decide(s)).toEqual({ type: 'play', cardIds: ['H9'] });
|
||||
});
|
||||
|
||||
test('declares one-card, getting rid of a joker that may not be the last card', () => {
|
||||
const s = rig(make(), { A: ['H9', 'JB'], B: ['C4', 'C5'], C: ['D9', 'D10'] }, ['H5']);
|
||||
expect(decide(s)).toEqual({ type: 'play', cardIds: ['JB'], declareOneCard: true });
|
||||
test('plays the joker that may not be the last card, then calls "원카드!" as its own action', () => {
|
||||
let s = rig(make(), { A: ['H9', 'JB'], B: ['C4', 'C5'], C: ['D9', 'D10'] }, ['H5']);
|
||||
expect(decide(s)).toEqual({ type: 'play', cardIds: ['JB'] });
|
||||
s = oneCard.apply(s, 'A', { type: 'play', cardIds: ['JB'] }, { rng: SeededRng.fromSeed(seedN(2)), now: 10 }).state;
|
||||
expect(oneCard.activePlayers(s)).toContain('A');
|
||||
expect(decide(s, 'A', 10)).toEqual({ type: 'declareOneCard' });
|
||||
});
|
||||
|
||||
test('a 7 changes to the suit it holds most of', () => {
|
||||
@@ -49,11 +53,50 @@ describe('one-card bot', () => {
|
||||
expect(decide(s)).toMatchObject({ type: 'play', cardIds: ['H7'], chooseSuit: 'C' });
|
||||
});
|
||||
|
||||
test("catches another player's missed one-card call", () => {
|
||||
test("catches another player's missed call once the protection time is over (only if it noticed)", () => {
|
||||
let s = rig(make(), { A: ['H9', 'C3'], B: ['C4', 'C5', 'S6'], C: ['D9', 'D10'] }, ['H5']);
|
||||
s = oneCard.apply(s, 'A', { type: 'play', cardIds: ['H9'] }, { rng: SeededRng.fromSeed(seedN(2)), now: 1 }).state;
|
||||
expect(s.oneCardWindow).toMatchObject({ player: 'A', declared: false });
|
||||
expect(decide(s, 'C')).toEqual({ type: 'declareOneCard' });
|
||||
// A window seq this computer notices (and one it misses) at level 30 (보통).
|
||||
const seqs = Array.from({ length: 60 }, (_, i) => i + 1);
|
||||
const seen = seqs.find((q) => noticesMissedCall('B', { seq: q }, 30))!;
|
||||
const missed = seqs.find((q) => !noticesMissedCall('B', { seq: q }, 30))!;
|
||||
s.oneCardWindow!.openedSeq = seen;
|
||||
// B's own turn: before 2 s it can't catch yet and just draws; after, it catches first.
|
||||
expect(decide(s, 'B', 500, 30)).toEqual({ type: 'draw' });
|
||||
expect(decide(s, 'B', 2001, 30)).toEqual({ type: 'declareOneCard' });
|
||||
s.oneCardWindow!.openedSeq = missed;
|
||||
expect(decide(s, 'B', 2001, 30)).toEqual({ type: 'draw' });
|
||||
});
|
||||
|
||||
test('reaction clock: own call by level (sometimes late), catches only after the protection time, misses by level', () => {
|
||||
let s = rig(make(), { A: ['H9', 'C3'], B: ['C4', 'C5', 'S6'], C: ['D9', 'D10'] }, ['H5']);
|
||||
s = oneCard.apply(s, 'A', { type: 'play', cardIds: ['H9'] }, { rng: SeededRng.fromSeed(seedN(2)), now: 1000 }).state;
|
||||
const react = (p: string, level?: number) => oneCardReaction({ me: p, view: oneCard.view(s, p), level });
|
||||
const w = { seq: s.oneCardWindow!.openedSeq };
|
||||
expect(react('A', 50)).toBe(Math.round(1000 + callDelayMs('A', w, 50)));
|
||||
const c = react('C', 50);
|
||||
expect(c === 'ignore' || (typeof c === 'number' && c >= 3000)).toBe(true);
|
||||
if (typeof c === 'number') expect(c).toBe(Math.round(3000 + catchDelayMs('C', w, 50)));
|
||||
// Same answer every time (the driver asks again when it fires).
|
||||
expect(react('C', 50)).toBe(c);
|
||||
// Statistics over many windows.
|
||||
const N = 2000;
|
||||
const avg = (f: (q: number) => number) => Array.from({ length: N }, (_, q) => f(q)).reduce((a, b) => a + b, 0) / N;
|
||||
const late = (level: number) => avg((q) => (callDelayMs('bot:1:x', { seq: q }, level) > 2000 ? 1 : 0));
|
||||
expect(late(55)).toBeGreaterThan(0.03);
|
||||
expect(late(55)).toBeLessThan(0.15);
|
||||
expect(late(30)).toBeGreaterThan(0.25);
|
||||
expect(late(10)).toBeGreaterThan(0.6);
|
||||
const notice = (level: number) => avg((q) => (noticesMissedCall('bot:2:y', { seq: q }, level) ? 1 : 0));
|
||||
expect(notice(55)).toBeGreaterThan(0.85);
|
||||
expect(notice(30)).toBeGreaterThan(0.6);
|
||||
expect(notice(30)).toBeLessThan(0.8);
|
||||
expect(notice(10)).toBeLessThan(0.55);
|
||||
// Nothing to react to once A has called.
|
||||
s = oneCard.apply(s, 'A', { type: 'declareOneCard' }, { rng: SeededRng.fromSeed(seedN(3)), now: 1500 }).state;
|
||||
expect(react('A')).toBeNull();
|
||||
expect(react('C')).toBeNull();
|
||||
});
|
||||
|
||||
test('colour cards: a wild picks the colour it holds most of', () => {
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
/**
|
||||
* 원카드 / 색깔 카드 computer player: always declare (and catch others' missed) one-card, counter attacks when it
|
||||
* can, otherwise play a matching card while keeping jokers / 7s / wilds for later; attack when the next player is
|
||||
* close to going out; a changed suit or colour is the one it holds most of.
|
||||
* 원카드 / 색깔 카드 computer player: calls its own "원카드!" and catches others' missed calls (how fast, and whether it
|
||||
* notices at all, depends on its level: `oneCardReaction`), counters attacks when it can, otherwise plays a matching
|
||||
* card while keeping jokers / 7s / wilds for later; attacks when the next player is close to going out; a changed
|
||||
* suit or colour is the one it holds most of.
|
||||
*/
|
||||
import type { BotStrategy } from '../bots/types';
|
||||
import type { BotReaction, BotStrategy } from '../bots/types';
|
||||
import type { BotLevel } from '../bots/persona';
|
||||
import { hash01 } from '../bots/persona';
|
||||
import { best, pick, playable, typeOf } from '../bots/policy';
|
||||
import { COLORS, SUITS, colorOf, isStd, type Card, type Color, type Suit } from './cards';
|
||||
import { attackOf, forbiddenAsLast } from './rules';
|
||||
@@ -27,15 +30,72 @@ function majority<K extends string>(keys: K[], all: K[], random: () => number):
|
||||
return best(all, (k) => count.get(k) ?? 0, random);
|
||||
}
|
||||
|
||||
export const oneCardBot: BotStrategy<OneCardView, OneCardAction> = ({ view, legal, random }) => {
|
||||
// ---------------------------------------------------------------- 원카드! reaction (docs/games/one-card.md §5.3)
|
||||
|
||||
type Window = NonNullable<OneCardView['oneCardWindow']>;
|
||||
const band = (level: BotLevel | undefined): 'hard' | 'normal' | 'easy' => (level === undefined || level > 40 ? 'hard' : level > 20 ? 'normal' : 'easy');
|
||||
|
||||
/**
|
||||
* How long after the window opened this computer calls its own "원카드!" (ms). Mostly quick, but like a person it is
|
||||
* sometimes slow: 쉬움 1.4~4 s (one in four times 5~9 s: forgot), 보통 0.9~2.8 s (sometimes 3~5 s), 어려움 0.5~1.5 s
|
||||
* (now and then 1.8~3.2 s). Fixed per window (same answer every time it is asked).
|
||||
*/
|
||||
export function callDelayMs(me: string, w: Pick<Window, 'seq'>, level: BotLevel | undefined): number {
|
||||
const r = hash01(me, w.seq, 'call');
|
||||
const slip = hash01(me, w.seq, 'slip');
|
||||
switch (band(level)) {
|
||||
case 'hard':
|
||||
return slip < 0.08 ? 1800 + r * 1400 : 500 + r * 1000;
|
||||
case 'normal':
|
||||
return slip < 0.12 ? 3000 + r * 2000 : 900 + r * 1900;
|
||||
case 'easy':
|
||||
return slip < 0.25 ? 5000 + r * 4000 : 1400 + r * 2600;
|
||||
}
|
||||
}
|
||||
|
||||
/** Does this computer notice that someone forgot to call (어려움 90%, 보통 70%, 쉬움 45%)? Fixed per window. */
|
||||
export function noticesMissedCall(me: string, w: Pick<Window, 'seq'>, level: BotLevel | undefined): boolean {
|
||||
const chance = { hard: 0.9, normal: 0.7, easy: 0.45 }[band(level)];
|
||||
return hash01(me, w.seq, 'notice') < chance;
|
||||
}
|
||||
|
||||
/** How long after the protection time it presses to catch (어려움 0.2~1.2 s, 보통 0.5~2.5 s, 쉬움 1~4 s). */
|
||||
export function catchDelayMs(me: string, w: Pick<Window, 'seq'>, level: BotLevel | undefined): number {
|
||||
const r = hash01(me, w.seq, 'catch');
|
||||
switch (band(level)) {
|
||||
case 'hard':
|
||||
return 200 + r * 1000;
|
||||
case 'normal':
|
||||
return 500 + r * 2000;
|
||||
case 'easy':
|
||||
return 1000 + r * 3000;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The bot driver asks this for every computer: when (server time) it reacts to an open "원카드!" window, 'ignore' when
|
||||
* it doesn't notice a missed call, null when there is nothing to react to.
|
||||
*/
|
||||
export const oneCardReaction: BotReaction<OneCardView> = ({ me, view, level }) => {
|
||||
const w = view.oneCardWindow;
|
||||
if (!w || w.declared || !view.my?.canDeclare) return null;
|
||||
if (w.player === me) return Math.round(w.openedAt + callDelayMs(me, w, level));
|
||||
if (!noticesMissedCall(me, w, level)) return 'ignore';
|
||||
return Math.round(Math.max(w.catchFrom, w.openedAt) + catchDelayMs(me, w, level));
|
||||
};
|
||||
|
||||
export const oneCardBot: BotStrategy<OneCardView, OneCardAction> = ({ me, view, legal, random, level }) => {
|
||||
const types = new Set(legal.map(typeOf));
|
||||
if (types.has('ready')) return { type: 'ready' };
|
||||
// My own one-card call, or catching someone who forgot to call it.
|
||||
if (types.has('declareOneCard')) return { type: 'declareOneCard' };
|
||||
// My own call first; a catch only when it noticed (before the protection time ends the server refuses it and the
|
||||
// bot just plays on). Returned as the listed action so a refused one is dropped from the retry.
|
||||
const call = legal.find((a) => a.type === 'declareOneCard');
|
||||
const w = view.oneCardWindow;
|
||||
if (call && w && (w.player === me || noticesMissedCall(me, w, level))) return call;
|
||||
|
||||
const hand = view.my?.hand ?? [];
|
||||
const byId = new Map(hand.map((c) => [c.id, c]));
|
||||
const plays = (legal.filter((a) => a.type === 'play') as PlayAction[]).filter((a) => a.declareOneCard || hand.length - a.cardIds.length !== 1);
|
||||
const plays = legal.filter((a) => a.type === 'play') as PlayAction[];
|
||||
const o = view.options;
|
||||
const uno = view.mode === 'uno-style';
|
||||
|
||||
|
||||
@@ -501,8 +501,9 @@ function playCards(s: OneCardState, p: PlayerId, a: PlayAction, ctx: Ctx): void
|
||||
}
|
||||
|
||||
if (handLeft === 1) {
|
||||
const declared = o.autoDeclare || !!a.declareOneCard;
|
||||
s.oneCardWindow = { player: p, declared, openedSeq: s.seq };
|
||||
// Calling is its own action now (§5.3): only the autoDeclare option calls together with the play.
|
||||
const declared = o.autoDeclare;
|
||||
s.oneCardWindow = { player: p, declared, openedSeq: s.seq, openedAt: ctx.now };
|
||||
ctx.events.push({ type: 'oneCardOpen', player: p, declared });
|
||||
if (declared) log(s, { t: 'declare', p });
|
||||
}
|
||||
@@ -594,6 +595,7 @@ function declareOneCard(s: OneCardState, actor: PlayerId, ctx: Ctx): void {
|
||||
w.declared = true;
|
||||
ctx.events.push({ type: 'oneCardDeclared', player: actor });
|
||||
log(s, { t: 'declare', p: actor });
|
||||
if (s.options.oneCardBonus) bonusDraws(s, actor, ctx);
|
||||
return;
|
||||
}
|
||||
const target = w.player;
|
||||
@@ -605,6 +607,24 @@ function declareOneCard(s: OneCardState, actor: PlayerId, ctx: Ctx): void {
|
||||
if (s.status[target] !== 'playing') repairAfterRemoval(s, target, ctx);
|
||||
}
|
||||
|
||||
/** oneCardBonus: everyone else still in the round takes 1 card, in turn order from the caller. */
|
||||
function bonusDraws(s: OneCardState, caller: PlayerId, ctx: Ctx): void {
|
||||
const order: PlayerId[] = [];
|
||||
for (let k = 1, i = s.seats.indexOf(caller); k < s.seats.length; k++) {
|
||||
const p = s.seats[(((i + k * s.direction) % s.seats.length) + s.seats.length) % s.seats.length]!;
|
||||
if (s.status[p] === 'playing') order.push(p);
|
||||
}
|
||||
for (const p of order) {
|
||||
if (s.phase.kind === 'finished' || s.phase.kind === 'roundEnd') return;
|
||||
if (s.status[p] !== 'playing') continue;
|
||||
drawCards(s, p, 1, 'bonus', ctx);
|
||||
if (s.status[p] !== 'playing') repairAfterRemoval(s, p, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
/** When others may catch the window's owner (server time). */
|
||||
export const catchFrom = (s: OneCardState): number => (s.oneCardWindow?.openedAt ?? 0) + s.options.oneCardGrace * 1000;
|
||||
|
||||
function leave(s: OneCardState, p: PlayerId, ctx: Ctx): void {
|
||||
s.leftOrder.push(p);
|
||||
ctx.events.push({ type: 'left', player: p });
|
||||
@@ -721,9 +741,11 @@ function deadlineMs(s: OneCardState): number | null {
|
||||
switch (s.phase.kind) {
|
||||
case 'turn':
|
||||
case 'afterDraw':
|
||||
return s.away[s.current] ? AWAY_MS : s.options.turnSeconds * 1000;
|
||||
if (s.away[s.current]) return AWAY_MS;
|
||||
return s.options.turnSeconds === null ? null : s.options.turnSeconds * 1000;
|
||||
case 'wild4Response':
|
||||
return s.away[s.phase.target] ? AWAY_MS : WILD4_MS;
|
||||
if (s.away[s.phase.target]) return AWAY_MS;
|
||||
return s.options.turnSeconds === null ? null : WILD4_MS;
|
||||
case 'roundEnd':
|
||||
return ROUND_END_MS;
|
||||
case 'finished':
|
||||
@@ -731,14 +753,13 @@ function deadlineMs(s: OneCardState): number | null {
|
||||
}
|
||||
}
|
||||
|
||||
/** All play actions for `p` built from a set of card ids (suits / colours / declare variants). */
|
||||
/** All play actions for `p` built from a set of card ids (suit / colour variants). */
|
||||
function playVariants(s: OneCardState, p: PlayerId, ids: string[]): PlayAction[] {
|
||||
const hand = s.hands[p]!;
|
||||
const first = hand.find((c) => c.id === ids[0])!;
|
||||
let out: PlayAction[] = [{ type: 'play', cardIds: ids }];
|
||||
if (isStd(first) && first.rank === 7) out = SUITS.map((chooseSuit: Suit) => ({ type: 'play', cardIds: ids, chooseSuit }));
|
||||
if (isWildKind(first)) out = COLORS.map((chooseColor: Color) => ({ type: 'play', cardIds: ids, chooseColor }));
|
||||
if (hand.length - ids.length === 1) out = out.flatMap((x) => [x, { ...x, declareOneCard: true }]);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -805,7 +826,7 @@ export const oneCard: GameDefinition<OneCardState, OneCardAction, OneCardView, O
|
||||
return s;
|
||||
},
|
||||
|
||||
validate(s, actor, a) {
|
||||
validate(s, actor, a, vctx) {
|
||||
if (!s.seats.includes(actor)) return fail('이 게임의 플레이어가 아니에요.');
|
||||
if (s.phase.kind === 'finished') return fail('게임이 이미 끝났어요.');
|
||||
if (a.type === 'leave') return gone(s, actor) ? fail('이미 나간 플레이어예요.') : ok;
|
||||
@@ -819,7 +840,10 @@ export const oneCard: GameDefinition<OneCardState, OneCardAction, OneCardView, O
|
||||
const w = s.oneCardWindow;
|
||||
if (!w || s.phase.kind === 'roundEnd') return fail('지금은 원카드를 외칠 때가 아니에요.');
|
||||
if (w.declared) return fail('이미 원카드를 외쳤어요.');
|
||||
return canDeclare(s, actor) ? ok : fail('게임에서 빠진 사람은 외칠 수 없어요.');
|
||||
if (!canDeclare(s, actor)) return fail('게임에서 빠진 사람은 외칠 수 없어요.');
|
||||
// Fair race (§5.3): the owner alone may call during the protection time; tests without a clock skip this.
|
||||
if (w.player !== actor && vctx && vctx.now < catchFrom(s)) return fail('아직 잡을 수 없어요. 1장 남은 사람이 먼저 외칠 시간이에요.');
|
||||
return ok;
|
||||
}
|
||||
case 'challengeWild4':
|
||||
case 'acceptWild4':
|
||||
@@ -970,7 +994,7 @@ export const oneCard: GameDefinition<OneCardState, OneCardAction, OneCardView, O
|
||||
pendingAttack: s.pendingAttack,
|
||||
drawPileCount: s.drawPile.length,
|
||||
discardCount: s.discard.length,
|
||||
oneCardWindow: w ? { player: w.player, declared: w.declared } : null,
|
||||
oneCardWindow: w ? { player: w.player, declared: w.declared, seq: w.openedSeq, openedAt: w.openedAt ?? 0, catchFrom: catchFrom(s) } : null,
|
||||
wild4: ph.kind === 'wild4Response' ? { by: ph.by, target: ph.target } : null,
|
||||
my,
|
||||
reveal: me && s.reveal && s.reveal.to === me ? { by: s.reveal.by, cards: s.reveal.cards, illegal: s.reveal.illegal } : null,
|
||||
@@ -983,9 +1007,14 @@ export const oneCard: GameDefinition<OneCardState, OneCardAction, OneCardView, O
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Whose move the game waits on, plus the owner of an open "원카드!" window (their call). Catching is open to everyone
|
||||
* but never awaited: computers catch on their own reaction clock (`oneCardReaction` in bot.ts).
|
||||
*/
|
||||
activePlayers(s) {
|
||||
const out = waiting(s);
|
||||
if (s.oneCardWindow && !s.oneCardWindow.declared) for (const p of s.seats) if (!out.includes(p) && !gone(s, p) && canDeclare(s, p)) out.push(p);
|
||||
const w = s.oneCardWindow;
|
||||
if (w && !w.declared && !out.includes(w.player) && !gone(s, w.player) && canDeclare(s, w.player)) out.push(w.player);
|
||||
return out;
|
||||
},
|
||||
|
||||
|
||||
@@ -279,7 +279,8 @@ describe('특수 카드 (§5.2 B·C)', () => {
|
||||
|
||||
test('lastCardRule = joker: [조커, ♥5] → ♥5 leaves the joker, which may not be played as the last card', () => {
|
||||
let s = rig(make({}, ['A', 'B']), { hands: { A: ['JB', 'H5'], B: ['H9', 'S9', 'C9'] }, discard: ['H8'] });
|
||||
s = play(s, 'A', ['H5'], { declareOneCard: true });
|
||||
s = play(s, 'A', ['H5']);
|
||||
s = act(s, 'A', { type: 'declareOneCard' });
|
||||
s = play(s, 'B', ['H9']);
|
||||
expect(reject(s, 'A', { type: 'play', cardIds: ['JB'] })).toBe('마지막 카드로 조커는 낼 수 없어요.');
|
||||
expect(oneCard.view(s, 'A').my!.legalCardIds).toEqual([]);
|
||||
@@ -317,7 +318,9 @@ describe('원카드 선언 (§5.3)', () => {
|
||||
test('caught: B presses first → A takes the penalty (1장) and the window closes', () => {
|
||||
let s = play(setupOne(), 'A', ['H5']);
|
||||
expect(s.oneCardWindow).toMatchObject({ player: 'A', declared: false });
|
||||
expect(oneCard.activePlayers(s).sort()).toEqual(['A', 'B', 'C']);
|
||||
// The game waits on A's call (and B's turn); catching is open to anyone but never awaited.
|
||||
expect(oneCard.activePlayers(s).sort()).toEqual(['A', 'B']);
|
||||
expect(oneCard.legalActions!(s, 'C')).toEqual([{ type: 'declareOneCard' }]);
|
||||
const out = actE(s, 'B', { type: 'declareOneCard' });
|
||||
s = out.state;
|
||||
expect(s.hands.A).toHaveLength(2);
|
||||
@@ -335,13 +338,48 @@ describe('원카드 선언 (§5.3)', () => {
|
||||
expect(JSON.stringify(s)).toBe(before);
|
||||
});
|
||||
|
||||
test('play with declareOneCard: true cannot be caught; autoDeclare does it for everyone', () => {
|
||||
const s = play(setupOne(), 'A', ['H5'], { declareOneCard: true });
|
||||
expect(reject(s, 'B', { type: 'declareOneCard' })).not.toBeNull();
|
||||
test('calling is its own action: a play never calls (an old client flag is dropped); only autoDeclare does', () => {
|
||||
const parsed = oneCard.actionSchema.parse({ type: 'play', cardIds: ['H5'], declareOneCard: true }) as Record<string, unknown>;
|
||||
expect(parsed.declareOneCard).toBeUndefined();
|
||||
const s = act(setupOne(), 'A', parsed as OneCardAction);
|
||||
expect(s.oneCardWindow).toMatchObject({ player: 'A', declared: false });
|
||||
expect(reject(s, 'B', { type: 'declareOneCard' })).toBeNull();
|
||||
// No "play and call" variants for the bots / the random playouts either.
|
||||
const two = setupOne();
|
||||
expect(oneCard.legalActions!(two, 'A').some((a) => 'declareOneCard' in a)).toBe(false);
|
||||
expect(reject(two, 'A', { type: 'declareOneCard' })).toBe('지금은 원카드를 외칠 때가 아니에요.');
|
||||
const auto = play(setupOne({ autoDeclare: true }), 'A', ['H5']);
|
||||
expect(auto.oneCardWindow?.declared).toBe(true);
|
||||
});
|
||||
|
||||
test('protection time: only the owner may call during the first oneCardGrace seconds, then anyone may catch', () => {
|
||||
const s = play(setupOne(), 'A', ['H5']);
|
||||
const opened = s.oneCardWindow!.openedAt!;
|
||||
expect(opened).toBe(clock);
|
||||
const at = (p: string, now: number) => {
|
||||
const v = oneCard.validate(s, p, { type: 'declareOneCard' }, { now });
|
||||
return v.ok ? null : v.reason;
|
||||
};
|
||||
expect(at('A', opened)).toBeNull();
|
||||
expect(at('B', opened + 1999)).toBe('아직 잡을 수 없어요. 1장 남은 사람이 먼저 외칠 시간이에요.');
|
||||
expect(at('B', opened + 2000)).toBeNull();
|
||||
expect(oneCard.view(s, 'B').oneCardWindow).toEqual({ player: 'A', declared: false, seq: s.seq, openedAt: opened, catchFrom: opened + 2000 });
|
||||
const quick = play(setupOne({ oneCardGrace: 1 }), 'A', ['H5']);
|
||||
expect(oneCard.validate(quick, 'C', { type: 'declareOneCard' }, { now: quick.oneCardWindow!.openedAt! + 1000 }).ok).toBe(true);
|
||||
});
|
||||
|
||||
test('oneCardBonus: calling first makes everyone else take 1 card', () => {
|
||||
let s = play(setupOne({ oneCardBonus: true }), 'A', ['H5']);
|
||||
const out = actE(s, 'A', { type: 'declareOneCard' });
|
||||
s = out.state;
|
||||
expect([s.hands.A!.length, s.hands.B!.length, s.hands.C!.length]).toEqual([1, 3, 3]);
|
||||
expect(s.log.filter((e) => e.t === 'draw' && e.why === 'bonus').map((e) => ('p' in e ? e.p : ''))).toEqual(['B', 'C']);
|
||||
expect(s.current).toBe('B');
|
||||
// Off by default.
|
||||
const plain = act(play(setupOne(), 'A', ['H5']), 'A', { type: 'declareOneCard' });
|
||||
expect(plain.hands.B).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('classic window lifetime and the colour-card rule (closes on the next player’s first action)', () => {
|
||||
let s = rig(make({}, ['A', 'B', 'C']), { hands: { A: ['H5', 'C9'], B: ['H9', 'S10', 'S4'], C: ['H10', 'D10', 'S3'] }, discard: ['H8'] });
|
||||
s = play(s, 'A', ['H5']);
|
||||
@@ -591,6 +629,17 @@ describe('색깔 카드 (§5.6)', () => {
|
||||
// ---------------------------------------------------------------- timers, leaving
|
||||
|
||||
describe('시간 초과, 연결 끊김, 나가기 (§8.5)', () => {
|
||||
test('turnSeconds null (무제한): no turn clock, no +4 clock; away players still get 5 s; the round pause stays', () => {
|
||||
const s = rig(make({ turnSeconds: null }), { hands: { A: ['H9', 'C4'], B: ['S9'] }, discard: ['H5'] });
|
||||
expect(oneCard.deadline!(s)).toBeNull();
|
||||
expect(oneCard.view(s, 'A').deadlineTotalMs).toBe(0);
|
||||
s.away.A = true;
|
||||
expect(oneCard.deadline!(s)).toBe(s.turnStartedAt + 5000);
|
||||
let u = rig(make({ mode: 'uno-style', unoWild4Rule: 'challenge', turnSeconds: null }), { hands: { A: ['F1', 'G1a'], B: ['Y1a'], C: ['Y3a'] }, discard: ['R5a'] });
|
||||
u = play(u, 'A', ['F1'], { chooseColor: 'G' });
|
||||
expect(oneCard.deadline!(u)).toBeNull();
|
||||
});
|
||||
|
||||
test('timeout while attacked → takes the attack; afterDraw → pass; wild4Response → accept', () => {
|
||||
let s = rig(make(), { hands: { A: ['H2', 'C4'], B: ['S2', 'S9'], C: ['D9'] }, discard: ['H5'] });
|
||||
s = play(s, 'A', ['H2']);
|
||||
@@ -807,7 +856,7 @@ function fastPlayout(players: PlayerId[], options: OneCardOptions, seed: RngStat
|
||||
const PRESETS: Record<'classic' | 'uno-style', Partial<OneCardOptions>[]> = {
|
||||
classic: [
|
||||
{},
|
||||
{ voluntaryDraw: false, multiPlay: true },
|
||||
{ voluntaryDraw: false, multiPlay: true, oneCardBonus: true, turnSeconds: null },
|
||||
{ kEffect: 'skip-two', qInTwoPlayer: 'as-skip', lastCardRule: 'special', afterJoker: 'any', threeDefense: 'off' },
|
||||
{ endCondition: 'last-standing', bankruptLimit: 15, handSize: 5, deckCount: 2, playAfterDraw: 'on' },
|
||||
{ multiPlay: true, lastCardRule: 'attack', bankruptLimit: 'none', autoDeclare: true, attackColorJoker: 13, attackSpadeA: 10 },
|
||||
@@ -815,7 +864,7 @@ const PRESETS: Record<'classic' | 'uno-style', Partial<OneCardOptions>[]> = {
|
||||
'uno-style': [
|
||||
{},
|
||||
{ voluntaryDraw: false, unoWild4Rule: 'challenge' },
|
||||
{ unoStacking: true, unoWild4Rule: 'challenge', bankruptLimit: 25, voluntaryDraw: false },
|
||||
{ unoStacking: true, unoWild4Rule: 'challenge', bankruptLimit: 25, voluntaryDraw: false, oneCardBonus: true, oneCardGrace: 1 },
|
||||
{ endCondition: 'last-standing', unoWild4Rule: 'free', bankruptLimit: 18, playAfterDraw: 'off', handSize: 5 },
|
||||
{ unoTargetScore: 200, voluntaryDraw: false, bankruptLimit: 20, autoDeclare: true },
|
||||
],
|
||||
|
||||
@@ -3,7 +3,7 @@ import { z } from 'zod';
|
||||
import type { PlayerId } from '@bg/engine';
|
||||
import type { Card, Color, Suit } from './cards';
|
||||
|
||||
const lit = <T extends string | number>(...vals: T[]) =>
|
||||
const lit = <T extends string | number | null>(...vals: T[]) =>
|
||||
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
||||
|
||||
export const oneCardOptionsSchema = z.object({
|
||||
@@ -47,7 +47,11 @@ export const oneCardOptionsSchema = z.object({
|
||||
oneCardPenalty: lit<'auto' | 1 | 2 | 3>('auto', 1, 2, 3)
|
||||
.default('auto')
|
||||
.meta({ title: '원카드를 못 외치고 잡히면 먹는 장수', labels: { auto: '모드 기본(원카드 1장, 색깔 카드 2장)', 1: '1장', 2: '2장', 3: '3장' } }),
|
||||
autoDeclare: z.boolean().default(false).meta({ title: '1장 남으면 자동으로 원카드 외치기' }),
|
||||
autoDeclare: z.boolean().default(false).meta({ title: '1장 남으면 자동으로 원카드 외치기(잡기 없음, 초보용)' }),
|
||||
oneCardGrace: lit(1, 2, 3)
|
||||
.default(2)
|
||||
.meta({ title: '원카드 잡기 전 보호 시간(1장 남은 사람만 외칠 수 있는 시간)', labels: { 1: '1초', 2: '2초', 3: '3초' } }),
|
||||
oneCardBonus: z.boolean().default(false).meta({ title: '원카드를 먼저 외치면 다른 사람이 1장씩 먹기' }),
|
||||
bankruptLimit: lit<'auto' | 15 | 18 | 20 | 25 | 'none'>('auto', 15, 18, 20, 25, 'none')
|
||||
.default('auto')
|
||||
.meta({
|
||||
@@ -62,9 +66,9 @@ export const oneCardOptionsSchema = z.object({
|
||||
.enum(['first-out', 'last-standing'])
|
||||
.default('first-out')
|
||||
.meta({ title: '끝나는 때', labels: { 'first-out': '1등이 나오면', 'last-standing': '꼴찌가 정해질 때까지' } }),
|
||||
turnSeconds: lit(10, 15, 20, 30, 60)
|
||||
turnSeconds: lit(10, 15, 20, 30, 60, null)
|
||||
.default(20)
|
||||
.meta({ title: '한 턴 제한 시간', labels: { 10: '10초', 15: '15초', 20: '20초', 30: '30초', 60: '60초' } }),
|
||||
.meta({ title: '한 턴 제한 시간', labels: { 10: '10초', 15: '15초', 20: '20초', 30: '30초', 60: '60초', null: '무제한' } }),
|
||||
unoStacking: z.boolean().default(false).meta({ title: '(색깔 카드) +2·+4 받아치기' }),
|
||||
unoWild4Rule: z
|
||||
.enum(['strict', 'challenge', 'free'])
|
||||
@@ -86,7 +90,6 @@ export const oneCardActionSchema = z.discriminatedUnion('type', [
|
||||
cardIds: z.array(z.string().max(8)).min(1).max(8),
|
||||
chooseSuit: z.enum(['S', 'H', 'D', 'C']).optional(),
|
||||
chooseColor: z.enum(['R', 'Y', 'G', 'B']).optional(),
|
||||
declareOneCard: z.boolean().optional(),
|
||||
}),
|
||||
z.object({ type: z.literal('draw') }),
|
||||
z.object({ type: z.literal('pass') }),
|
||||
@@ -113,7 +116,7 @@ export type Phase =
|
||||
export type LogEntry =
|
||||
/** Played cards without ids: ids are reused after a reshuffle and must not hint at hidden cards. */
|
||||
| { seq: number; t: 'play'; p: PlayerId; cards: CardFace[]; suit?: Suit; color?: Color }
|
||||
| { seq: number; t: 'draw'; p: PlayerId; n: number; why: 'normal' | 'attack' | 'penalty' | 'draw2' | 'wild4' | 'challenge' | 'start' }
|
||||
| { seq: number; t: 'draw'; p: PlayerId; n: number; why: 'normal' | 'attack' | 'penalty' | 'bonus' | 'draw2' | 'wild4' | 'challenge' | 'start' }
|
||||
| { seq: number; t: 'pass'; p: PlayerId }
|
||||
| { seq: number; t: 'blocked'; p: PlayerId }
|
||||
| { seq: number; t: 'declare'; p: PlayerId }
|
||||
@@ -171,7 +174,11 @@ export interface OneCardState {
|
||||
phase: Phase;
|
||||
pendingAttack: number;
|
||||
extraTurn: boolean;
|
||||
oneCardWindow: { player: PlayerId; declared: boolean; openedSeq: number } | null;
|
||||
/**
|
||||
* "원카드!" window (§5.3): opens when a play leaves exactly one card. `openedAt` = server time it opened; others may
|
||||
* catch only after the protection time (`oneCardGrace`). Missing `openedAt` (older saves) = catchable at once.
|
||||
*/
|
||||
oneCardWindow: { player: PlayerId; declared: boolean; openedSeq: number; openedAt?: number } | null;
|
||||
status: Record<PlayerId, PlayerStatus>;
|
||||
finishOrder: PlayerId[];
|
||||
bankruptOrder: PlayerId[];
|
||||
@@ -234,7 +241,8 @@ export interface OneCardView {
|
||||
pendingAttack: number;
|
||||
drawPileCount: number;
|
||||
discardCount: number;
|
||||
oneCardWindow: { player: PlayerId; declared: boolean } | null;
|
||||
/** `catchFrom`: server time from which other players may catch (the owner may call at once). `seq` names the window. */
|
||||
oneCardWindow: { player: PlayerId; declared: boolean; seq: number; openedAt: number; catchFrom: number } | null;
|
||||
wild4: { by: PlayerId; target: PlayerId } | null;
|
||||
my: {
|
||||
hand: Card[];
|
||||
|
||||
Reference in New Issue
Block a user