Compare commits
46 Commits
84d64b27f2
...
d35b7207a3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d35b7207a3 | ||
|
|
2489627bcd | ||
|
|
606756868c | ||
|
|
91fcf1c83d | ||
|
|
647e9bd448 | ||
|
|
764de1fe1a | ||
|
|
43291606ce | ||
|
|
085ddbaec3 | ||
|
|
99c25cb260 | ||
|
|
b6b9dbc963 | ||
|
|
8cde4fa525 | ||
|
|
4fa4c69725 | ||
|
|
36c8033b65 | ||
|
|
92c9a41d83 | ||
|
|
28590df429 | ||
|
|
743e5dc05e | ||
|
|
2136916a28 | ||
|
|
94f7120a51 | ||
|
|
a6ace5b5e8 | ||
|
|
1b4c80a2df | ||
|
|
f6a0cdcf14 | ||
|
|
8175cebd2c | ||
|
|
ac37a6a6d8 | ||
|
|
b8966db2a6 | ||
|
|
5e1e74da18 | ||
|
|
bafbf95d98 | ||
|
|
ec4c849096 | ||
|
|
0a406306da | ||
|
|
f620faf70b | ||
|
|
f053b8fc6b | ||
|
|
f12cf12b84 | ||
|
|
544f704397 | ||
|
|
89312e28f2 | ||
|
|
71381087cc | ||
|
|
65c56d3ae7 | ||
|
|
115969515c | ||
|
|
74a7daa4d3 | ||
|
|
bde430f33e | ||
|
|
609f458ed2 | ||
|
|
cf7523f862 | ||
|
|
3fffcec52b | ||
|
|
c9f81804cf | ||
|
|
b98775b0a6 | ||
|
|
2ec622ebf6 | ||
|
|
bd179c7a43 | ||
|
|
2fe43952d3 |
15
README.md
@@ -5,20 +5,21 @@
|
||||
|
||||
운영 중: https://game.tkrmagid.kr
|
||||
|
||||
## 게임 (26개)
|
||||
## 게임 (33개)
|
||||
| 종류 | 게임 |
|
||||
|---|---|
|
||||
| 2인 수 싸움 | 오목, 오셀로, 체스(체스960 포함), 장기, 바둑, 쿼리도(2·4명) |
|
||||
| 카드·화투 | 원카드, 섯다, 포커, 고스톱, 달무티, 구십구, 바퀴벌레 포커, 뱅! |
|
||||
| 타일·주사위 | 루미큐브, 다빈치 코드, 마작, 요트 다이스, 윷놀이, 라스베가스, 부루마불, 스플렌더 |
|
||||
| 순발력·대화 | 할리갈리, 도블, 그림 맞히기, 마피아 |
|
||||
| 2인 수 싸움 | 오목, 커넥트 포(사목), 오셀로, 체스(체스960 포함), 장기, 바둑, 쿼리도(2·4명) |
|
||||
| 카드·화투 | 원카드, 우노, 도둑잡기, 섯다, 포커, 고스톱, 달무티, 구십구, 바퀴벌레 포커, 뱅! |
|
||||
| 타일·주사위·판 | 루미큐브, 다빈치 코드, 마작, 요트 다이스, 윷놀이(지역 룰 선택), 라스베가스, 부루마불, 스플렌더, 야단법석 달리기, 클루 |
|
||||
| 순발력·대화 | 할리갈리, 도블, 그림 맞히기, 사과 게임, 마피아, 라이어 게임 |
|
||||
|
||||
칩·포인트·지폐는 모두 놀이용이다(실제 돈과 무관).
|
||||
칩·포인트·지폐, 섯다의 "원"은 모두 놀이용이다(실제 돈과 무관, 충전·환전 없음).
|
||||
|
||||
## 주요 기능
|
||||
- 로그인: 디스코드 또는 게스트(닉네임만). 게스트는 로그아웃하거나 하루 동안 접속하지 않으면 계정이 지워진다.
|
||||
- 방: 방 링크를 보내면 친구가 바로 들어온다. 방 막대에서 링크 복사·채팅·규칙·설정(글자 크기·소리)·나가기를 한 번에 누른다. 게임 중에 나가면 기권으로 처리된다.
|
||||
- 컴퓨터 상대: 실시간·대화 게임(할리갈리, 도블, 그림 맞히기, 마피아)을 뺀 22개 게임.
|
||||
- 모든 게임에 효과음과 움직임(상대·컴퓨터의 수에도 나옴), 오른쪽 위 소리 크기(0~100, 기본 50). 시간 제한이 있는 게임은 모두 "무제한"도 고를 수 있다.
|
||||
- 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)을 뺀 30개 게임. 마피아·라이어 게임의 컴퓨터는 채팅으로 말하고, 다른 게임의 컴퓨터 잡담은 방장이 켤 때만.
|
||||
- 처음 하는 사람을 위한 30초 규칙 요약, 게임별 규칙 페이지, 끝난 판 다시 보기, 이름을 누르면 나오는 기록 카드.
|
||||
- 홈 화면에 추가(PWA), 휴대폰(320px부터)·PC, 다크 모드.
|
||||
- 관리자 화면(`/admin`): 게임 규칙 기본값·잠금, 사용자·방 관리, 계정별 기록.
|
||||
|
||||
298
apps/server/src/ai/acts.ts
Normal file
@@ -0,0 +1,298 @@
|
||||
/**
|
||||
* What a move means, for the computers' talk (docs/06 §12.1): the model is told what someone did *and what it says
|
||||
* about them* (풀 베팅 = 세게 나옴, 다이 = 물러섬), and a line that contradicts it ("풀 베팅이라니 쫄았네") is thrown
|
||||
* away. Also the public facts of the table (칩·점수·카드 수) so the computers talk about this game, not in general.
|
||||
*/
|
||||
|
||||
/** strong = 세게·자신 있게 나옴, weak = 물러섬·포기, careful = 조심·지켜봄, neutral = 그냥 둔 수. */
|
||||
export type Tone = 'strong' | 'weak' | 'careful' | 'neutral';
|
||||
|
||||
/**
|
||||
* What kind of event a move is, for the built-in lines: the betting moves each have their own (센 베팅 = raise,
|
||||
* 콜 = call, 체크·삥 = check, 다이·폴드 = fold); other moves go by tone (bold = 고·론·우노 외침…, safe = 스톱·넘김,
|
||||
* giveUp = 기권). neutral = an ordinary move (a stone, a card): no line of its own.
|
||||
*/
|
||||
export type ActKind = 'raise' | 'call' | 'check' | 'fold' | 'bold' | 'safe' | 'giveUp' | 'neutral';
|
||||
|
||||
export interface ActMeaning {
|
||||
/** A few words for the move, e.g. "풀 베팅". */
|
||||
ko: string;
|
||||
/** What it means, for the model. */
|
||||
mean?: string;
|
||||
tone: Tone;
|
||||
/** Worth a word on its own (big bets, giving up, 고/스톱, …). Ordinary moves never get one. */
|
||||
notable: boolean;
|
||||
kind: ActKind;
|
||||
}
|
||||
|
||||
const TONE_KIND: Record<Tone, ActKind> = { strong: 'bold', weak: 'giveUp', careful: 'safe', neutral: 'neutral' };
|
||||
|
||||
const m = (ko: string, tone: Tone = 'neutral', notable = false, mean?: string, kind: ActKind = TONE_KIND[tone]): ActMeaning => ({
|
||||
ko,
|
||||
tone,
|
||||
notable,
|
||||
kind,
|
||||
...(mean ? { mean } : {}),
|
||||
});
|
||||
|
||||
const BET_TONE: Record<'raise' | 'call' | 'check' | 'fold', [Tone, boolean]> = {
|
||||
raise: ['strong', true],
|
||||
call: ['neutral', false],
|
||||
check: ['careful', false],
|
||||
fold: ['weak', true],
|
||||
};
|
||||
/** A betting move (섯다·포커): 센 베팅, 콜, 체크·삥, 다이·폴드. */
|
||||
const bet = (ko: string, kind: keyof typeof BET_TONE, mean: string): ActMeaning => m(ko, BET_TONE[kind][0], BET_TONE[kind][1], mean, kind);
|
||||
|
||||
const FULL = '판돈만큼 더 거는 가장 센 베팅. 패에 자신 있거나 세게 블러핑하는 공격적인 수다(겁먹은 게 아니다)';
|
||||
const HALF = '판돈의 절반을 더 걸며 크게 올림. 자신 있다는 뜻의 센 수다';
|
||||
const DIE = '이번 판을 포기하고 패를 접음. 물러선 것이다';
|
||||
const QUARTER = '판돈의 4분의 1을 더 걸며 올림. 세게 나온 수다';
|
||||
const DDADANG = '앞사람 베팅의 두 배로 올림. 세게 나온 것';
|
||||
const RAISE = '베팅을 올림. 자신 있다는 뜻의 센 수';
|
||||
const ALL_IN = '가진 것을 전부 검. 가장 센 승부수(겁먹은 게 아니다)';
|
||||
const CALL = '앞사람이 건 만큼 따라감. 승부를 받아들인 것';
|
||||
const CHECK = '더 걸지 않고 지켜봄. 조심스러운 수';
|
||||
const PING = '가장 작은 베팅으로 간을 봄. 조심스러운 수';
|
||||
const GIVE_UP = '이 판을 포기함';
|
||||
|
||||
/** Any game, by action type. */
|
||||
const COMMON: Record<string, ActMeaning> = {
|
||||
place: m('돌을 놓음'), drop: m('돌을 떨어뜨림'), move: m('말을 움직임'), MOVE: m('말을 움직임'), placeWall: m('벽을 세움'), castle: m('캐슬링'),
|
||||
play: m('카드를 냄'), discard: m('패를 버림'), DISCARD: m('패를 버림'), draw: m('패를 가져옴'), pass: m('넘김', 'careful'), PASS: m('넘김', 'careful'),
|
||||
// 섯다 (한게임식 이름: 삥·콜·따당·쿼터·하프·풀·다이)
|
||||
call: bet('콜', 'call', CALL),
|
||||
check: bet('체크', 'check', CHECK),
|
||||
ping: bet('삥', 'check', PING),
|
||||
die: bet('다이', 'fold', DIE),
|
||||
quarter: bet('쿼터 베팅', 'raise', QUARTER),
|
||||
half: bet('하프 베팅', 'raise', HALF),
|
||||
ddadang: bet('따당', 'raise', DDADANG),
|
||||
full: bet('풀 베팅', 'raise', FULL),
|
||||
raise: bet('레이즈', 'raise', RAISE),
|
||||
allIn: bet('올인', 'raise', ALL_IN),
|
||||
fold: bet('폴드', 'fold', DIE),
|
||||
roll: m('주사위를 굴림'), ROLL: m('주사위를 굴림'), hold: m('주사위를 고정함'), score: m('점수를 적음'),
|
||||
guess: m('추리함'), stop: m('추리를 멈춤', 'careful', true, '맞힌 뒤 더 노리지 않고 멈춤. 안전하게 간 것'),
|
||||
continue: m('계속 추리', 'strong', true, '맞힌 뒤 멈추지 않고 한 번 더 노림. 과감한 수'),
|
||||
offer: m('카드를 건넴'), peek: m('카드를 몰래 봄'), claim: m('선언함', 'strong', true), declare: m('선언함'),
|
||||
tsumo: m('쯔모', 'strong', true, '직접 뽑은 패로 났음'), ring: m('종을 침', 'strong', true), flip: m('카드를 뒤집음'),
|
||||
BUY: m('땅을 삼'), BUILD: m('건물을 지음'), sell: m('패를 팖'), SELL: m('땅을 팖', 'weak', false, undefined, 'neutral'),
|
||||
TAKEOVER: m('땅을 인수함', 'strong', true, '남의 땅을 빼앗아 옴'),
|
||||
THROW: m('윷을 던짐'), commit: m('타일을 내려놓음'), respond: m('대답함'), choose: m('골랐음'), vote: m('투표'),
|
||||
declareOneCard: m('원카드를 외침', 'strong', true, '카드가 한 장 남았다'), callUno: m('우노를 외침', 'strong', true, '카드가 한 장 남았다'),
|
||||
catchUno: m('우노 안 외친 사람을 잡음', 'strong', true), challenge: m('도전함', 'strong', true),
|
||||
accuse: m('최종 추리를 함', 'strong', true, '범인을 확신하고 승부를 건 것'),
|
||||
resign: m('기권', 'weak', true, GIVE_UP), concede: m('기권', 'weak', true, GIVE_UP), CONCEDE: m('기권', 'weak', true, GIVE_UP),
|
||||
giveUp: m('포기', 'weak', true, GIVE_UP),
|
||||
offerDraw: m('무승부를 제안함', 'careful', true), requestUndo: m('무르기를 부탁함', 'weak', true, undefined, 'neutral'),
|
||||
// 포커 (한국식 / 노리밋)
|
||||
'k.check': bet('체크', 'check', CHECK),
|
||||
'k.ping': bet('삥', 'check', PING),
|
||||
'k.call': bet('콜', 'call', CALL),
|
||||
'k.ddadang': bet('따당', 'raise', DDADANG),
|
||||
'k.quarter': bet('쿼터 베팅', 'raise', QUARTER),
|
||||
'k.half': bet('하프 베팅', 'raise', HALF),
|
||||
'k.full': bet('풀 베팅', 'raise', FULL),
|
||||
'k.die': bet('다이', 'fold', DIE),
|
||||
'nl.fold': bet('폴드', 'fold', DIE),
|
||||
'nl.check': bet('체크', 'check', CHECK),
|
||||
'nl.call': bet('콜', 'call', CALL),
|
||||
'nl.raise': bet('레이즈', 'raise', RAISE),
|
||||
'nl.allIn': bet('올인', 'raise', ALL_IN),
|
||||
};
|
||||
|
||||
/** Every move type the computers know the meaning of (for tests). */
|
||||
export const KNOWN_ACTIONS: readonly string[] = Object.keys(COMMON);
|
||||
|
||||
/** The meaning of `action` in `gameId` (payload-aware where one type covers opposite moves). */
|
||||
export function meaningOf(gameId: string, action: unknown): ActMeaning {
|
||||
const a = (action ?? {}) as { type?: string; decision?: string; call?: string; bet?: unknown; kind?: unknown; choice?: unknown };
|
||||
const type = String(a.type ?? '');
|
||||
if (gameId === 'gostop' && type === 'goStop') {
|
||||
return a.decision === 'go'
|
||||
? m('고', 'strong', true, '점수가 났는데 멈추지 않고 더 노림. 배짱 있는 수')
|
||||
: m('스톱', 'careful', true, '점수를 확정하고 판을 끝냄. 안전하게 간 것');
|
||||
}
|
||||
if (gameId === 'mahjong' && type === 'claim') {
|
||||
return a.call === 'ron' ? m('론', 'strong', true, '남이 버린 패로 났음') : m(`${a.call === 'pon' ? '퐁' : a.call === 'kan' ? '깡' : '치'}`, 'neutral');
|
||||
}
|
||||
if (gameId === 'dobble' && type === 'claim') return m('같은 그림을 찾음', 'strong');
|
||||
if (gameId === 'davinci-code' && type === 'guess') return m('상대 숫자를 추리함');
|
||||
if (COMMON[type]) return COMMON[type];
|
||||
// One action type for every bet with the bet in the payload ({ type: 'bet', bet: 'half' }).
|
||||
for (const k of [a.bet, a.kind, a.choice]) if (typeof k === 'string' && COMMON[k]) return COMMON[k];
|
||||
return m('수를 둠');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- contradictions
|
||||
|
||||
/** "겁먹었다", said about someone. */
|
||||
const FEAR = /쫄(?!깃)|겁\s?(먹|쟁이|나서|났|나냐|나지)|무서(웠|워서|워\s*[?ㅋ]|우냐|운가|운\s?거|운\s?가)|떨(려|리|고\s?있)|소심|도망|꽁무니|엄살/;
|
||||
/** "세게 나왔다", said about someone. */
|
||||
const BOLD = /세게|세다|과감|질렀|지르|지른|배짱|대담|공격적|화끈|자신감|용감|올인|풀\s?베팅|풀베|크게\s?(걸|건|질|나)/;
|
||||
/** "I'm scared / giving up", said about oneself while making a strong move. */
|
||||
const SELF_WEAK = /포기|접을|접어야|무섭|무서워|겁나|떨려|자신\s?없/;
|
||||
/** Bet names: a line naming another bet than the one made is talking about something that did not happen. */
|
||||
const BET_WORDS: [string, RegExp][] = [
|
||||
['다이', /다이/], ['콜', /콜(?!라)/], ['체크', /체크/], ['하프', /하프/], ['풀', /풀\s?(베팅|뱃|로)|풀베/], ['따당', /따당/],
|
||||
['삥', /삥/], ['쿼터', /쿼터/], ['올인', /올인/], ['폴드', /폴드/], ['레이즈', /레이즈/],
|
||||
];
|
||||
const betNames = (s: string) => BET_WORDS.filter(([, re]) => re.test(s)).map(([w]) => w);
|
||||
|
||||
/**
|
||||
* True when `line` says something the move contradicts. `mine` = the speaker made the move (taunting the others as
|
||||
* scared is fine then); otherwise the line is about the person who moved. `known` = other move names that came up
|
||||
* just before (a line may mention those).
|
||||
*/
|
||||
export function contradicts(line: string, meaning: ActMeaning, mine: boolean, known: string[] = []): boolean {
|
||||
if (meaning.tone === 'strong' && (mine ? SELF_WEAK : FEAR).test(line)) return true;
|
||||
if ((meaning.tone === 'weak' || meaning.tone === 'careful') && BOLD.test(line)) return true;
|
||||
const own = betNames(meaning.ko);
|
||||
if (!own.length) return false; // not a betting move: bet names don't apply
|
||||
const ok = new Set([...own, ...known.flatMap(betNames)]);
|
||||
return BET_WORDS.some(([w, re]) => re.test(line) && !ok.has(w));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- built-in lines
|
||||
|
||||
type Pool = { smart: string[]; casual: string[] };
|
||||
|
||||
/**
|
||||
* Built-in lines per kind of event, about someone else's move (`other`, `{who}` = that person) or one's own
|
||||
* (`mine`); `{act}` = the move's name (콜, 하프 베팅, 다이…). Said when the model is slow, down, or wrote a line
|
||||
* that contradicts the move — each one fits only its kind (no "쫄았네" on a raise, no "세게 나오네" on a fold;
|
||||
* tests check every line against `contradicts`). Ordinary moves (`neutral`) have none.
|
||||
*/
|
||||
const LINES: Partial<Record<ActKind, { other: Pool; mine: Pool }>> = {
|
||||
raise: {
|
||||
other: {
|
||||
casual: ['오 {who}, {act}? 세게 나오네 ㅋㅋ', '{act}? 패가 좋은가 보네 ㅋㅋ', '{who} 자신 있나 본데? 판이 커졌다 ㅋㅋ'],
|
||||
smart: ['{who}님, {act}? 세게 나오시네요.', '{act}? 패가 좋으신가 봐요.', '{who}님 자신 있으신가 봐요. 판이 커졌네요.'],
|
||||
},
|
||||
mine: {
|
||||
casual: ['{act} 간다! 따라올 수 있어? ㅋㅋ', '나는 {act}! 받을 거야? ㅋㅋ', '이번 판은 세게 간다 ㅋㅋ'],
|
||||
smart: ['{act} 갈게요. 따라오실 건가요?', '저는 {act}! 받으실 건가요?', '이번 판은 세게 가 볼게요.'],
|
||||
},
|
||||
},
|
||||
call: {
|
||||
other: {
|
||||
casual: ['{who}, {act} 받았네? 승부 보자는 거지 ㅋㅋ', '{act}? 좋아, 끝까지 가 보자 ㅋㅋ'],
|
||||
smart: ['{who}님, {act} 받으셨네요. 승부 보시죠.', '{act}? 좋아요, 끝까지 가 봐요.'],
|
||||
},
|
||||
mine: {
|
||||
casual: ['{act}! 어디 패 한번 보자 ㅋㅋ', '받아 줄게, {act}!'],
|
||||
smart: ['{act}할게요. 패 한번 봐요.', '받아 드릴게요, {act}!'],
|
||||
},
|
||||
},
|
||||
check: {
|
||||
other: {
|
||||
casual: ['{who}, {act}? 간 보는 거야? ㅋㅋ', '{act}? 조심하는데? ㅋㅋ'],
|
||||
smart: ['{who}님, {act}? 간 보시는 건가요?', '{act}? 조심스럽게 가시네요.'],
|
||||
},
|
||||
mine: {
|
||||
casual: ['일단 {act}. 천천히 가자 ㅋㅋ', '{act}! 아직은 지켜볼게'],
|
||||
smart: ['일단 {act}할게요.', '{act}! 아직은 지켜볼게요.'],
|
||||
},
|
||||
},
|
||||
fold: {
|
||||
other: {
|
||||
casual: ['{who} 이번엔 {act}? 다음 판에 보자 ㅋㅋ', '{act}? 현명한 선택일지도 ㅋㅋ'],
|
||||
smart: ['{who}님은 이번엔 물러나시는군요.', '{act}? 다음 판을 노리시는군요.'],
|
||||
},
|
||||
mine: {
|
||||
casual: ['이번 판은 {act}. 다음에 보자 ㅋㅋ', '아 이건 아니다, {act}!'],
|
||||
smart: ['이번 판은 {act}할게요.', '이번엔 물러날게요. 다음 판에 봬요.'],
|
||||
},
|
||||
},
|
||||
bold: {
|
||||
other: {
|
||||
casual: ['오 {who}, 과감한데? ㅋㅋ', '{who} 제법인데? 나도 질 수 없지 ㅋㅋ'],
|
||||
smart: ['{who}님, 과감하시네요.', '{who}님 제법이신데요? 저도 질 수 없죠.'],
|
||||
},
|
||||
mine: {
|
||||
casual: ['간다! 이번 판은 내가 가져간다 ㅋㅋ', '이 정도는 해 줘야지 ㅋㅋ'],
|
||||
smart: ['가 볼게요! 이번엔 제가 가져갈게요.', '이 정도는 해 봐야죠.'],
|
||||
},
|
||||
},
|
||||
safe: {
|
||||
other: {
|
||||
casual: ['{who}, 안전하게 가네? ㅋㅋ', '{who} 신중한데?'],
|
||||
smart: ['{who}님, 안전하게 가시네요.', '{who}님 신중하시네요.'],
|
||||
},
|
||||
mine: {
|
||||
casual: ['여기선 안전하게 갈게 ㅋㅋ', '욕심은 여기까지 ㅋㅋ'],
|
||||
smart: ['여기선 안전하게 갈게요.', '욕심은 여기까지만 낼게요.'],
|
||||
},
|
||||
},
|
||||
giveUp: {
|
||||
other: {
|
||||
casual: ['{who}, 이번 판은 여기까지야? 아쉽다', '{who} 다음 판에 또 하자 ㅋㅋ'],
|
||||
smart: ['{who}님, 이번 판은 여기까지인가요?', '아쉽네요, 다음 판에 또 해요!'],
|
||||
},
|
||||
mine: {
|
||||
casual: ['이번 판은 내가 졌다 ㅋㅋ 다음 판!', '여기까지! 다음 판에 보자'],
|
||||
smart: ['이번 판은 제가 졌네요. 다음 판에 봬요.', '여기까지 할게요. 다음 판에 봬요.'],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/** Every built-in line for `meaning` (about `who`'s move, or one's own when `mine`); empty for ordinary moves. */
|
||||
export function cannedLines(meaning: ActMeaning, who: string, smart: boolean, mine: boolean): string[] {
|
||||
const pool = LINES[meaning.kind]?.[mine ? 'mine' : 'other'][smart ? 'smart' : 'casual'] ?? [];
|
||||
return pool.map((l) => l.replaceAll('{who}', who).replaceAll('{act}', meaning.ko));
|
||||
}
|
||||
|
||||
/** One built-in line for the move (null for ordinary moves). */
|
||||
export function cannedLine(meaning: ActMeaning, who: string, smart: boolean, mine: boolean, random: () => number): string | null {
|
||||
const all = cannedLines(meaning, who, smart, mine);
|
||||
return all.length ? all[Math.floor(random() * all.length) % all.length]! : null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- facts
|
||||
|
||||
const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null);
|
||||
|
||||
/**
|
||||
* Public facts of the table as `bot` sees them, in short Korean: 판돈, each player's 칩/돈/점수/카드 수, who has
|
||||
* folded. Read from the common shapes of the games' views (`seats`/`players` with ids, `money`, `sheets`, `pot`);
|
||||
* hidden things (anyone's hand) are never read. Empty when the view has none of these.
|
||||
*/
|
||||
export function tableFacts(view: unknown, bot: string, nameOf: (id: string) => string): string[] {
|
||||
if (!view || typeof view !== 'object') return [];
|
||||
const v = view as Record<string, unknown>;
|
||||
const out: string[] = [];
|
||||
const pot = num(v.pot);
|
||||
if (pot !== null && pot > 0) out.push(`판돈 ${pot}`);
|
||||
const who = (id: string) => (id === bot ? `${nameOf(id)}(나)` : nameOf(id));
|
||||
const rows = (Array.isArray(v.seats) ? v.seats : Array.isArray(v.players) ? v.players : []) as Record<string, unknown>[];
|
||||
const per: string[] = [];
|
||||
for (const r of rows) {
|
||||
if (!r || typeof r !== 'object' || typeof r.id !== 'string') continue;
|
||||
const bits: string[] = [];
|
||||
const stack = num(r.stack);
|
||||
if (stack !== null) bits.push(`칩 ${stack}`);
|
||||
const cash = num(r.cash);
|
||||
if (cash !== null) bits.push(`돈 ${cash}`);
|
||||
const score = num(r.score) ?? num(r.total);
|
||||
if (score !== null) bits.push(`${score}점`);
|
||||
const cards = num(r.cards) ?? num(r.handCount);
|
||||
if (cards !== null) bits.push(`카드 ${cards}장`);
|
||||
const tiles = num(r.tiles);
|
||||
if (tiles !== null) bits.push(`타일 ${tiles}장`);
|
||||
if (r.folded === true) bits.push('다이함');
|
||||
if (r.allIn === true) bits.push('올인함');
|
||||
if (bits.length) per.push(`${who(r.id)} ${bits.join(' ')}`);
|
||||
}
|
||||
for (const [key, label] of [['money', '돈'], ['sheets', '점']] as const) {
|
||||
const rec = v[key];
|
||||
if (!per.length && rec && typeof rec === 'object' && !Array.isArray(rec)) {
|
||||
for (const [id, x] of Object.entries(rec as Record<string, unknown>)) {
|
||||
const n = num(x) ?? num((x as { total?: unknown } | null)?.total);
|
||||
if (n !== null) per.push(label === '점' ? `${who(id)} ${n}점` : `${who(id)} 돈 ${n}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (per.length) out.push(per.slice(0, 6).join(', '));
|
||||
return out;
|
||||
}
|
||||
@@ -6,7 +6,8 @@ import { openDb } from '../db';
|
||||
import { RoomManager } from '../rooms/manager';
|
||||
import type { Room } from '../rooms/room';
|
||||
import { RoomStore } from '../rooms/store';
|
||||
import { BotBrain } from './brain';
|
||||
import { cannedLines, contradicts, KNOWN_ACTIONS, meaningOf, tableFacts, type ActKind } from './acts';
|
||||
import { ANSWERS_PER_MINUTE, BotBrain, TALK_BOT_GAP, TALK_ROOM_GAP, type BrainRoom } from './brain';
|
||||
import { cleanLine, temperOf, TEMPERS } from './lines';
|
||||
import { Llm } from './llm';
|
||||
|
||||
@@ -109,28 +110,27 @@ function harness(reply: (user: string, body: { format?: unknown }) => string | E
|
||||
const settle = () => new Promise((r) => setTimeout(r, 5));
|
||||
|
||||
describe('rooms with the model', () => {
|
||||
test('omok: the computer thinks (visible), types a taunt in the chat, then moves', async () => {
|
||||
test('omok: the computer thinks (visible) and moves; an ordinary move gets no word on its own (신고: 혼잣말)', async () => {
|
||||
const h = harness((u) => (u.includes('할 말') ? '흐음, 여기 두면 아프겠는데?' : '좋아'));
|
||||
const room = h.manager.createPractice('A', 'omok') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } });
|
||||
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' }, botChat: true });
|
||||
expect(room.start('A')).toBeNull();
|
||||
await settle();
|
||||
h.clock.advance(TALK_BOT_GAP);
|
||||
room.act('A', 1, { type: 'place', x: 7, y: 7 });
|
||||
const activity = a.msgs.filter((m) => m.t === 'room').map((m) => (m as { room: { botActivity?: Record<string, string> } }).room.botActivity ?? {});
|
||||
expect(activity.some((x) => Object.values(x).includes('thinking'))).toBe(true);
|
||||
room.bots.fire();
|
||||
for (let i = 0; i < 20 && (room.game!.state as { moves: unknown[] }).moves.length < 2; i++) await settle();
|
||||
expect((room.game!.state as { moves: unknown[] }).moves).toHaveLength(2);
|
||||
const chats = a.msgs.filter((m) => m.t === 'chat') as { from: { id: string } | null; text: string }[];
|
||||
expect(chats.some((c) => c.from && isBotId(c.from.id) && c.text === '흐음, 여기 두면 아프겠는데?')).toBe(true);
|
||||
// It typed for a while before sending, and "입력 중" was shown then cleared.
|
||||
expect(h.slept.some((ms) => ms >= 900)).toBe(true);
|
||||
// No greeting, no word with a stone: the model was only warmed up.
|
||||
expect(a.msgs.some((m) => m.t === 'chat')).toBe(false);
|
||||
expect(h.prompts.every((p) => !p.includes('할 말'))).toBe(true);
|
||||
const last = a.msgs.filter((m) => m.t === 'room').at(-1) as { room: { botActivity?: object } };
|
||||
expect(last.room.botActivity).toBeUndefined();
|
||||
expect(h.prompts.some((p) => p.includes('오목'))).toBe(true);
|
||||
});
|
||||
|
||||
test('a person asks a computer by name: it answers in the room chat', async () => {
|
||||
@@ -139,6 +139,7 @@ describe('rooms with the model', () => {
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
room.configure('A', { botChat: true });
|
||||
expect(room.start('A')).toBeNull();
|
||||
room.chat('A', '컴퓨터 1 오목 잘해?');
|
||||
for (let i = 0; i < 20 && !a.msgs.some((m) => m.t === 'chat' && (m as { text: string }).text.startsWith('저요?')); i++) await settle();
|
||||
@@ -172,6 +173,7 @@ describe('rooms with the model', () => {
|
||||
rooms.push(room);
|
||||
const a = h.conn(`A${attempt}`);
|
||||
room.join(a, 'player');
|
||||
room.configure(`A${attempt}`, { botChat: true });
|
||||
expect(room.start(`A${attempt}`)).toBeNull();
|
||||
const st = () => room.game!.state as { round: { claim: string | null; card: string | null; starter: string } };
|
||||
if (!isBotId(st().round.starter)) continue;
|
||||
@@ -190,6 +192,59 @@ describe('rooms with the model', () => {
|
||||
expect(checked).toBe(true);
|
||||
});
|
||||
|
||||
test('컴퓨터 채팅 off (the default): computers never talk on their own — no taunts, answers, greetings or end words', async () => {
|
||||
const h = harness(() => '흐음, 여기 두면 아프겠는데?', () => 0);
|
||||
const room = h.manager.createPractice('A', 'omok') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.roomView().botChat).toBe(false);
|
||||
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } });
|
||||
expect(room.start('A')).toBeNull();
|
||||
await settle();
|
||||
room.chat('A', '컴퓨터 1 오목 잘해?');
|
||||
for (let i = 0; i < 3; i++) {
|
||||
room.act('A', i + 1, { type: 'place', x: [0, 14, 0][i]!, y: [0, 14, 14][i]! });
|
||||
room.bots.fire();
|
||||
for (let k = 0; k < 20 && (room.game!.state as { moves: unknown[] }).moves.length < 2 * (i + 1); k++) await settle();
|
||||
}
|
||||
expect((room.game!.state as { moves: unknown[] }).moves.length).toBe(6);
|
||||
expect(a.msgs.some((m) => m.t === 'chat' && (m as { from: { id: string } | null }).from && isBotId((m as { from: { id: string } }).from.id))).toBe(false);
|
||||
// The model isn't even warmed up: nothing in this game uses it.
|
||||
expect(h.prompts).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('컴퓨터 채팅 off: in 바퀴벌레 포커 the model still decides truth or bluff, the computer just says nothing', async () => {
|
||||
let checked = false;
|
||||
for (let attempt = 0; attempt < 12 && !checked; attempt++) {
|
||||
const h = harness((_u, body) => (body.format ? JSON.stringify({ bluff: false, say: '이건 진짜야, 믿어봐~' }) : '흠'));
|
||||
const room = h.manager.createPractice(`B${attempt}`, 'cockroach-poker') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn(`B${attempt}`);
|
||||
room.join(a, 'player');
|
||||
expect(room.start(`B${attempt}`)).toBeNull();
|
||||
const st = () => room.game!.state as { round: { claim: string | null; card: string | null; starter: string } };
|
||||
if (!isBotId(st().round.starter)) continue;
|
||||
for (let i = 0; i < 30 && !st().round.claim; i++) {
|
||||
room.bots.fire();
|
||||
await settle();
|
||||
}
|
||||
expect(st().round.claim).toBe(st().round.card!.replace(/-\d+$/, ''));
|
||||
expect(a.msgs.some((m) => m.t === 'chat')).toBe(false);
|
||||
checked = true;
|
||||
}
|
||||
expect(checked).toBe(true);
|
||||
});
|
||||
|
||||
test('마피아 needs its computers to talk: 컴퓨터 채팅 is always on there', () => {
|
||||
const h = harness(() => '흠');
|
||||
const room = h.manager.createPractice('A', 'mafia') as Room;
|
||||
rooms.push(room);
|
||||
room.join(h.conn('A'), 'player');
|
||||
room.configure('A', { botChat: false });
|
||||
expect(room.roomView().botChat).toBe(true);
|
||||
});
|
||||
|
||||
test('마피아: a computer says its planned line in its own words; a line claiming a role is thrown away', async () => {
|
||||
let n = 0;
|
||||
const h = harness(() => (n++ % 2 === 0 ? '안녕하세요~ 오늘 마피아 꼭 잡아봐요!' : '저 경찰이에요 믿어주세요'));
|
||||
@@ -211,11 +266,402 @@ describe('rooms with the model', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('BotBrain typing time grows with the line and stays human (0.9~6.5 s)', () => {
|
||||
test('BotBrain typing time grows with the line and stays quick (0.7~3.5 s)', () => {
|
||||
const brain = new BotBrain({} as never, null);
|
||||
const short = brain.typingMs('bot:1:x', 'ㅋㅋ');
|
||||
const long = brain.typingMs('bot:1:x', '이번 판은 내가 무조건 이긴다 각오해라 진짜로');
|
||||
expect(short).toBeGreaterThanOrEqual(900);
|
||||
expect(short).toBeGreaterThanOrEqual(700);
|
||||
expect(long).toBeGreaterThan(short);
|
||||
expect(long).toBeLessThanOrEqual(6500);
|
||||
for (let i = 0; i < 50; i++) expect(brain.typingMs(`bot:${i}:x`, '가'.repeat(40))).toBeLessThanOrEqual(3500);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- talking (fake room, fake model)
|
||||
|
||||
|
||||
/**
|
||||
* A BotBrain on a fake room: 철수 (A) with `bots` computers at 섯다. The model answers with `reply(prompt)`. Typing
|
||||
* advances the room clock; `hold` keeps a computer typing until `release()`.
|
||||
*/
|
||||
function talkHarness(
|
||||
reply: (user: string) => string | Error,
|
||||
opts: { bots?: number; humans?: string[]; random?: () => number; game?: string; llm?: (fetchFn: typeof fetch) => Llm | null } = {},
|
||||
) {
|
||||
let now = 1_000_000;
|
||||
const bots = Array.from({ length: opts.bots ?? 2 }, (_, i) => `bot:${i + 1}:x`);
|
||||
const humans = opts.humans ?? ['A'];
|
||||
const chats: { from: string; text: string; at: number }[] = [];
|
||||
const activity: { bot: string; a: string | null; at: number }[] = [];
|
||||
let hold: Promise<void> | null = null;
|
||||
let release = () => {};
|
||||
const { fetchFn, prompts } = fakeOllama((u) => reply(u));
|
||||
const llm = opts.llm ? opts.llm(fetchFn) : new Llm({ url: 'http://gpu', model: 'gemma3:4b', fetch: fetchFn });
|
||||
const view = { pot: 120, seats: [{ id: 'A', stack: 800, folded: false }, ...bots.map((b) => ({ id: b, stack: 500, folded: false }))] };
|
||||
const room: BrainRoom = {
|
||||
gameId: () => opts.game ?? 'seotda',
|
||||
gameName: () => '섯다',
|
||||
nameOf: (id) => (id === 'A' ? '철수' : id === 'B' ? '영희' : `컴퓨터 ${id.split(':')[1]}`),
|
||||
humans: () => humans,
|
||||
bots: () => bots,
|
||||
playing: () => true,
|
||||
roomChat: (bot, text) => void chats.push({ from: bot, text, at: now }),
|
||||
setActivity: (bot, a) => void activity.push({ bot, a, at: now }),
|
||||
recentChat: () => chats.slice(-8).map((c) => ({ from: c.from, text: c.text })),
|
||||
smart: () => false,
|
||||
chatty: () => true,
|
||||
now: () => now,
|
||||
view: () => view,
|
||||
};
|
||||
const brain = new BotBrain(room, llm, opts.random ?? (() => 0), async (ms) => {
|
||||
now += ms;
|
||||
if (hold) await hold;
|
||||
});
|
||||
return {
|
||||
brain,
|
||||
bots,
|
||||
chats,
|
||||
activity,
|
||||
prompts,
|
||||
advance: (ms: number) => (now += ms),
|
||||
now: () => now,
|
||||
holdTyping: () => {
|
||||
hold = new Promise<void>((r) => (release = () => ((hold = null), r())));
|
||||
},
|
||||
release: () => release(),
|
||||
/** Lets the fake model and typing finish. */
|
||||
flush: async () => {
|
||||
for (let i = 0; i < 12; i++) await new Promise((r) => setImmediate(r));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('answering people (신고: 한 번 답하고 그 뒤로 답장이 없음)', () => {
|
||||
test('every message to a computer gets an answer — named once, then just talking to it', async () => {
|
||||
let n = 0;
|
||||
// random 0.99: nothing is left to chance (the old code answered an unnamed line only 40% of the time).
|
||||
const h = talkHarness(() => `대답 ${++n}번째 ㅋㅋ`, { random: () => 0.99 });
|
||||
const msgs = ['컴퓨터1 뒤질래?', '왜 대답 안해', 'ㅋㅋ 너 지금 쫄았지?', '야', '이번 판 누가 이길 것 같아?'];
|
||||
for (const text of msgs) {
|
||||
h.brain.onHumanChat('A', text);
|
||||
await h.flush();
|
||||
h.advance(4000);
|
||||
}
|
||||
expect(h.chats.map((c) => c.from)).toEqual(msgs.map(() => 'bot:1:x'));
|
||||
expect(h.chats).toHaveLength(msgs.length);
|
||||
// Each prompt carries the person's message.
|
||||
for (const text of msgs) expect(h.prompts.some((p) => p.includes(text))).toBe(true);
|
||||
});
|
||||
|
||||
test('a message while the computer is typing is answered right after it, not dropped; a burst gets one answer', async () => {
|
||||
const h = talkHarness((u) => (u.includes('뒤질래') ? '어휴 무섭네 ㅋㅋ' : u.includes('세 번째') ? '세 번째에 대답 ㅋㅋ' : '첫 마디 ㅋㅋ'));
|
||||
h.holdTyping();
|
||||
h.brain.onHumanChat('A', '컴퓨터 1 안녕');
|
||||
await h.flush();
|
||||
expect(h.chats).toHaveLength(0); // still typing
|
||||
h.brain.onHumanChat('A', '컴퓨터1 뒤질래?');
|
||||
h.brain.onHumanChat('A', '컴퓨터1 두 번째');
|
||||
h.brain.onHumanChat('A', '컴퓨터1 세 번째');
|
||||
h.release();
|
||||
await h.flush();
|
||||
expect(h.chats.map((c) => c.text)).toEqual(['첫 마디 ㅋㅋ', '세 번째에 대답 ㅋㅋ']);
|
||||
});
|
||||
|
||||
test('the model writes something unusable (rude, echo): the computer still answers, with a safe line', async () => {
|
||||
const h = talkHarness(() => '철수 이 망할 놈! 닥쳐 ㅋㅋ');
|
||||
h.brain.onHumanChat('A', '컴퓨터1 뒤질래?');
|
||||
await h.flush();
|
||||
expect(h.chats).toHaveLength(1);
|
||||
expect(h.chats[0]!.text).not.toMatch(/놈|닥쳐/);
|
||||
});
|
||||
|
||||
test('with two people, an unnamed line is not taken as talking to a computer (unless it answers one)', async () => {
|
||||
const h = talkHarness(() => '응 ㅋㅋ', { humans: ['A', 'B'], random: () => 0.99 });
|
||||
h.brain.onHumanChat('A', '영희야 이번 판 어때');
|
||||
await h.flush();
|
||||
expect(h.chats).toHaveLength(0);
|
||||
h.brain.onHumanChat('A', '컴퓨터 2 너는?');
|
||||
await h.flush();
|
||||
expect(h.chats.map((c) => c.from)).toEqual(['bot:2:x']);
|
||||
h.advance(5000);
|
||||
h.brain.onHumanChat('B', 'ㅋㅋ 진짜?'); // right after 컴퓨터 2 spoke: an answer to it
|
||||
await h.flush();
|
||||
expect(h.chats.map((c) => c.from)).toEqual(['bot:2:x', 'bot:2:x']);
|
||||
});
|
||||
|
||||
test('quick: "입력 중…" shows at once, a short answer is up within 3 s and a long one within 3.5 s', async () => {
|
||||
for (const [line, limit] of [['ㅋㅋ 내가 이기지', 3000], ['이번 판은 칩 많은 내가 무조건 가져간다 각오해 ㅋㅋ', 3500]] as const) {
|
||||
const h = talkHarness(() => line);
|
||||
const t0 = h.now();
|
||||
h.brain.onHumanChat('A', '컴퓨터1 누가 이겨?');
|
||||
// Before the model has answered: typing already shows.
|
||||
expect(h.activity[0]).toEqual({ bot: 'bot:1:x', a: 'typing', at: t0 });
|
||||
await h.flush();
|
||||
expect(h.chats).toHaveLength(1);
|
||||
expect(h.chats[0]!.at - t0).toBeLessThanOrEqual(limit);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('answering without a quick model (신고: 답장이 느림)', () => {
|
||||
test('no model at all: every message to a computer still gets a fitting built-in answer, fast', async () => {
|
||||
const h = talkHarness(() => 'x', { llm: () => null });
|
||||
const msgs = ['컴퓨터1 뒤질래?', '왜 대답 안해', '컴퓨터1 안녕', '이번 판 누가 이길 것 같아?'];
|
||||
for (const text of msgs) {
|
||||
const t0 = h.now();
|
||||
h.brain.onHumanChat('A', text);
|
||||
await h.flush();
|
||||
expect(h.chats.at(-1)!.at - t0).toBeLessThanOrEqual(3500);
|
||||
h.advance(4000);
|
||||
}
|
||||
expect(h.chats.map((c) => c.from)).toEqual(msgs.map(() => 'bot:1:x'));
|
||||
const [jab, , hello, question] = h.chats.map((c) => c.text);
|
||||
expect(['ㅋㅋ 말로 하지 말고 게임으로 해!', '워워~ 판에서 보자 ㅋㅋ']).toContain(jab!);
|
||||
expect(['ㅎㅇ! 잘 해 보자 ㅋㅋ', '안녕~ 한 판 붙자!']).toContain(hello!);
|
||||
expect(['ㅋㅋ 글쎄~ 두고 봐', '비밀이지롱~', '끝나 보면 알겠지 ㅋㅋ']).toContain(question!);
|
||||
for (const c of h.chats) expect(cleanLine(c.text)).toBe(c.text);
|
||||
});
|
||||
|
||||
test('a hung model: the built-in answer is up within the wait (2.5 s), not after the model gives up', async () => {
|
||||
const hang = (async (_u: string, init: RequestInit) =>
|
||||
new Promise((_, rej) => init.signal!.addEventListener('abort', () => rej(new Error('aborted'))))) as unknown as typeof fetch;
|
||||
const h = talkHarness(() => 'x', { llm: () => new Llm({ url: 'http://gpu', model: 'm', fetch: hang, timeoutMs: 3000 }) });
|
||||
const t0 = Date.now();
|
||||
h.brain.onHumanChat('A', '컴퓨터1 뭐해?');
|
||||
for (let i = 0; i < 400 && !h.chats.length; i++) await new Promise((r) => setTimeout(r, 10));
|
||||
expect(h.chats).toHaveLength(1);
|
||||
expect(Date.now() - t0).toBeLessThan(2900);
|
||||
expect(h.activity[0]!.a).toBe('typing'); // "입력 중…" from the start
|
||||
});
|
||||
|
||||
test('a flood is cut off: at most a few answers a minute to one person', async () => {
|
||||
const h = talkHarness(() => '응 ㅋㅋ');
|
||||
for (let i = 0; i < 40; i++) {
|
||||
h.brain.onHumanChat('A', `컴퓨터1 ${i}`);
|
||||
await h.flush();
|
||||
h.advance(1500);
|
||||
}
|
||||
expect(h.chats.length).toBeGreaterThanOrEqual(ANSWERS_PER_MINUTE);
|
||||
expect(h.chats.length).toBeLessThanOrEqual(ANSWERS_PER_MINUTE * 2);
|
||||
});
|
||||
|
||||
test('two people: after a computer answered, the next line is an answer to it — later lines between people are not', async () => {
|
||||
const h = talkHarness(() => '응 ㅋㅋ', { humans: ['A', 'B'], random: () => 0.99 });
|
||||
h.brain.onHumanChat('A', '컴퓨터 2 너는?');
|
||||
await h.flush();
|
||||
h.advance(3000);
|
||||
h.brain.onHumanChat('B', 'ㅋㅋ 진짜?');
|
||||
await h.flush();
|
||||
expect(h.chats).toHaveLength(2);
|
||||
h.advance(1000);
|
||||
h.brain.onHumanChat('A', '영희야 우리 둘이 하자');
|
||||
h.brain.onHumanChat('B', '그래 좋아');
|
||||
await h.flush();
|
||||
expect(h.chats).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('talking on its own (신고: 게임과 상관없는 혼잣말만 엄청함)', () => {
|
||||
test('rare: over 10 minutes of busy play at most one line per 40 s in the room and per 90 s per computer', async () => {
|
||||
const h = talkHarness(() => '판돈 커졌네 ㅋㅋ 받아줄게');
|
||||
for (let t = 0; t < 600_000; t += 2000) {
|
||||
h.brain.onAction('A', { type: t % 4000 ? 'half' : 'call' });
|
||||
for (const b of h.bots) await h.brain.beforeMove(b, { type: 'full' }, {});
|
||||
await h.flush();
|
||||
h.advance(2000);
|
||||
}
|
||||
const lines = h.chats.length;
|
||||
expect(lines).toBeGreaterThan(0);
|
||||
expect(lines).toBeLessThanOrEqual(Math.ceil(700_000 / TALK_ROOM_GAP));
|
||||
for (const b of h.bots) expect(h.chats.filter((c) => c.from === b).length).toBeLessThanOrEqual(Math.ceil(700_000 / TALK_BOT_GAP));
|
||||
for (let i = 1; i < h.chats.length; i++) expect(h.chats[i]!.at - h.chats[i - 1]!.at).toBeGreaterThanOrEqual(TALK_ROOM_GAP - 4000);
|
||||
});
|
||||
|
||||
test("a person's ordinary move never gets a word on its own", async () => {
|
||||
const h = talkHarness(() => '판돈 커졌네 ㅋㅋ');
|
||||
for (let i = 0; i < 30; i++) {
|
||||
h.brain.onAction('A', { type: 'call' });
|
||||
h.brain.onAction('A', { type: 'check' });
|
||||
await h.flush();
|
||||
h.advance(30_000);
|
||||
}
|
||||
expect(h.chats).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('the prompt has the facts: who did what, what it means, the pot and stacks', async () => {
|
||||
const h = talkHarness(() => '오 철수 세게 나오네 ㅋㅋ');
|
||||
h.brain.onAction('A', { type: 'full' });
|
||||
await h.flush();
|
||||
const p = h.prompts.at(-1)!;
|
||||
expect(p).toContain('철수: 풀 베팅 — 판돈만큼 더 거는 가장 센 베팅');
|
||||
expect(p).toContain('판돈 120');
|
||||
expect(p).toContain('컴퓨터 1(나) 칩 500');
|
||||
expect(h.chats.map((c) => c.text)).toEqual(['오 철수 세게 나오네 ㅋㅋ']);
|
||||
});
|
||||
|
||||
test('a line about nothing in this game ("다들 준비됐냐?") is not said: a line for the move is said instead', async () => {
|
||||
const h = talkHarness(() => '흥, 또 시작이네 ㅋㅋ 다들 준비됐냐?');
|
||||
await h.brain.beforeMove('bot:1:x', { type: 'full' }, {});
|
||||
h.advance(TALK_ROOM_GAP);
|
||||
h.brain.onAction('A', { type: 'die' });
|
||||
await h.flush();
|
||||
expect(h.chats.map((c) => c.text)).toEqual([
|
||||
cannedLines(meaningOf('seotda', { type: 'full' }), '컴퓨터 1', false, true)[0]!,
|
||||
cannedLines(meaningOf('seotda', { type: 'die' }), '철수', false, false)[0]!,
|
||||
]);
|
||||
expect(h.chats.some((c) => c.text.includes('준비'))).toBe(false);
|
||||
});
|
||||
|
||||
test('without the model the computers play silently; a notable move gets a word only while the model is up', async () => {
|
||||
const h = talkHarness(() => new Error('down'));
|
||||
for (let i = 0; i < 4; i++) {
|
||||
h.brain.onAction('A', { type: 'full' });
|
||||
await h.flush();
|
||||
h.advance(TALK_BOT_GAP);
|
||||
}
|
||||
// The model failed three times and is backing off: no more words on its own (the first ones were built-in lines).
|
||||
const said = h.chats.length;
|
||||
expect(said).toBeLessThanOrEqual(3);
|
||||
for (const c of h.chats) expect(cannedLines(meaningOf('seotda', { type: 'full' }), '철수', false, false)).toContain(c.text);
|
||||
h.brain.onAction('A', { type: 'full' });
|
||||
await h.flush();
|
||||
expect(h.chats).toHaveLength(said);
|
||||
});
|
||||
});
|
||||
|
||||
describe('lines that contradict the move (신고: 풀 베팅인데 "쫄았네")', () => {
|
||||
test('풀 베팅 → "쫄았네" is thrown away and a safe line said instead; 다이 → "세게 나오네" likewise', async () => {
|
||||
const h = talkHarness(() => 'ㅋㅋ 풀 베팅이라니, 완전 쫄앗네 풉!');
|
||||
h.brain.onAction('A', { type: 'full' });
|
||||
await h.flush();
|
||||
expect(h.chats.map((c) => c.text)).toEqual(['오 철수, 풀 베팅? 세게 나오네 ㅋㅋ']);
|
||||
const d = talkHarness(() => '철수 오늘 세게 나오네 ㅋㅋ');
|
||||
d.brain.onAction('A', { type: 'die' });
|
||||
await d.flush();
|
||||
expect(d.chats.map((c) => c.text)).toEqual(['철수 이번엔 다이? 다음 판에 보자 ㅋㅋ']);
|
||||
});
|
||||
|
||||
test('my own 풀 베팅 with "무섭다, 포기할까" or a wrong bet name is not said (a line for a raise is)', async () => {
|
||||
for (const bad of ['아 무섭다 그냥 포기할까 ㅋㅋ', '다이할게 판돈 가져가라 ㅋㅋ']) {
|
||||
const h = talkHarness(() => bad);
|
||||
await h.brain.beforeMove('bot:1:x', { type: 'full' }, {});
|
||||
await h.flush();
|
||||
expect(h.chats.map((c) => c.text)).toEqual(['풀 베팅 간다! 따라올 수 있어? ㅋㅋ']);
|
||||
}
|
||||
});
|
||||
|
||||
test('each kind of move has its own lines, and every line fits only its kind (no "쫄" on a raise)', () => {
|
||||
const kinds: Record<string, ActKind> = {
|
||||
half: 'raise', full: 'raise', ddadang: 'raise', quarter: 'raise', 'k.half': 'raise', 'k.full': 'raise', 'k.ddadang': 'raise',
|
||||
'nl.raise': 'raise', 'nl.allIn': 'raise', call: 'call', 'k.call': 'call', 'nl.call': 'call',
|
||||
check: 'check', ping: 'check', 'k.check': 'check', 'k.ping': 'check', 'nl.check': 'check', die: 'fold', 'k.die': 'fold', 'nl.fold': 'fold',
|
||||
};
|
||||
for (const [type, kind] of Object.entries(kinds)) expect([type, meaningOf('seotda', { type }).kind]).toEqual([type, kind]);
|
||||
// A rebuilt game may put the bet in the payload.
|
||||
expect(meaningOf('seotda', { type: 'bet', bet: 'half' }).kind).toBe('raise');
|
||||
expect(meaningOf('seotda', { type: 'bet', kind: 'die' }).kind).toBe('fold');
|
||||
const SCARED = /쫄|겁|무서|소심|도망|엄살|떨/;
|
||||
const BRAVE = /세게|과감|질렀|배짱|화끈|자신|올인|풀\s?베팅/;
|
||||
const metas = [
|
||||
...KNOWN_ACTIONS.map((type) => meaningOf('seotda', { type })),
|
||||
meaningOf('gostop', { type: 'goStop', decision: 'go' }),
|
||||
meaningOf('gostop', { type: 'goStop', decision: 'stop' }),
|
||||
meaningOf('mahjong', { type: 'claim', call: 'ron' }),
|
||||
];
|
||||
let checked = 0;
|
||||
for (const meaning of metas) {
|
||||
for (const smart of [true, false]) {
|
||||
for (const mine of [true, false]) {
|
||||
const lines = cannedLines(meaning, '철수', smart, mine);
|
||||
// Notable moves always have a fitting line (unless deliberately neutral); ordinary moves never get one.
|
||||
if (meaning.kind === 'neutral') expect(lines).toEqual([]);
|
||||
else expect(lines.length).toBeGreaterThan(1);
|
||||
for (const line of lines) {
|
||||
checked++;
|
||||
expect([meaning.ko, line, contradicts(line, meaning, mine)]).toEqual([meaning.ko, line, false]);
|
||||
expect(cleanLine(line, 40)).toBe(line);
|
||||
if (meaning.kind === 'raise' || meaning.kind === 'bold') expect([meaning.ko, line, SCARED.test(line)]).toEqual([meaning.ko, line, false]);
|
||||
if (['fold', 'check', 'safe', 'giveUp', 'call'].includes(meaning.kind)) expect([meaning.ko, line, BRAVE.test(line)]).toEqual([meaning.ko, line, false]);
|
||||
// A 존댓말 computer never talks down.
|
||||
if (smart) expect(line).toMatch(/요|죠/);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(checked).toBeGreaterThan(150);
|
||||
});
|
||||
|
||||
test('every kind of bet, with the model writing the opposite: the line said fits the bet', async () => {
|
||||
const wrong: Record<string, string> = {
|
||||
full: 'ㅋㅋ 풀 베팅이라니, 완전 쫄았네 풉!',
|
||||
half: '겁먹었구나 철수 ㅋㅋ 하프 베팅',
|
||||
ddadang: '따당? 떨고 있네 ㅋㅋ',
|
||||
die: '다이? 와 과감하게 질렀네 ㅋㅋ',
|
||||
check: '체크? 화끈하게 지르네 ㅋㅋ',
|
||||
ping: '삥이라니 배짱 좋네 ㅋㅋ',
|
||||
};
|
||||
for (const [type, bad] of Object.entries(wrong)) {
|
||||
const h = talkHarness(() => bad);
|
||||
h.brain.onAction('A', { type });
|
||||
await h.flush();
|
||||
const meaning = meaningOf('seotda', { type });
|
||||
if (!meaning.notable) {
|
||||
expect(h.chats).toHaveLength(0); // 체크·삥: ordinary, no word at all
|
||||
continue;
|
||||
}
|
||||
expect(h.chats).toHaveLength(1);
|
||||
expect(cannedLines(meaning, '철수', false, false)).toContain(h.chats[0]!.text);
|
||||
}
|
||||
});
|
||||
|
||||
test('rules: who made the move matters; other games are not judged by bet names', () => {
|
||||
const full = meaningOf('seotda', { type: 'full' });
|
||||
const die = meaningOf('seotda', { type: 'die' });
|
||||
expect(contradicts('ㅋㅋ 풀 베팅이라니, 완전 쫄앗네 풉!', full, false)).toBe(true);
|
||||
expect(contradicts('겁먹었냐? ㅋㅋ', full, false)).toBe(true);
|
||||
expect(contradicts('내 풀 베팅에 쫄았지? ㅋㅋ', full, true)).toBe(false); // my big bet, the others scared: fine
|
||||
expect(contradicts('오 세게 나오네 판돈 커졌다', full, false)).toBe(false);
|
||||
expect(contradicts('벌써 다이야? 쫄았구나 ㅋㅋ', die, false)).toBe(false);
|
||||
expect(contradicts('와 과감하게 질렀네', die, false)).toBe(true);
|
||||
expect(contradicts('하프 베팅이라니 대단해', full, false)).toBe(true); // a bet that wasn't made
|
||||
expect(contradicts('하프 받고 풀 베팅 간다', full, true, ['하프 베팅'])).toBe(false); // it was, just before
|
||||
expect(contradicts('여기 두면 아프겠는데? 체크야', meaningOf('omok', { type: 'place' }), true)).toBe(false);
|
||||
expect(meaningOf('poker', { type: 'k.full' }).tone).toBe('strong');
|
||||
expect(meaningOf('gostop', { type: 'goStop', decision: 'go' }).ko).toBe('고');
|
||||
expect(meaningOf('gostop', { type: 'goStop', decision: 'stop' }).tone).toBe('careful');
|
||||
});
|
||||
|
||||
test('table facts read only public numbers (stacks, scores, card counts), never a hand', () => {
|
||||
const names = (id: string) => (id === 'A' ? '철수' : '컴퓨터 1');
|
||||
expect(tableFacts({ pot: 30, seats: [{ id: 'A', stack: 990, folded: true, cards: [{ hidden: true }] }, { id: 'bot:1:x', stack: 980 }], myHand: { name: '38광땡' } }, 'bot:1:x', names)).toEqual([
|
||||
'판돈 30',
|
||||
'철수 칩 990 다이함, 컴퓨터 1(나) 칩 980',
|
||||
]);
|
||||
expect(tableFacts({ seats: [{ id: 'A', cards: 3, score: 10 }] }, 'bot:1:x', names)).toEqual(['철수 10점 카드 3장']);
|
||||
expect(tableFacts({ sheets: { A: { total: 120 } } }, 'bot:1:x', names)).toEqual(['철수 120점']);
|
||||
expect(tableFacts(null, 'bot:1:x', names)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Llm queue (one GPU slot)', () => {
|
||||
test('one request at a time; an answer to a person goes ahead of waiting talk; talk is dropped when busy', async () => {
|
||||
const order: string[] = [];
|
||||
let open = 0;
|
||||
let maxOpen = 0;
|
||||
const fetchFn = (async (_u: string, init: RequestInit) => {
|
||||
const body = JSON.parse(String(init.body)) as { messages: { content: string }[]; options: { stop?: string[] } };
|
||||
open++;
|
||||
maxOpen = Math.max(maxOpen, open);
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
order.push(body.messages[0]!.content);
|
||||
open--;
|
||||
return new Response(JSON.stringify({ message: { content: 'ok' } }));
|
||||
}) as unknown as typeof fetch;
|
||||
const llm = new Llm({ url: 'http://x', model: 'm', fetch: fetchFn });
|
||||
const first = llm.chat([{ role: 'user', content: 'first' }]);
|
||||
const normal = llm.chat([{ role: 'user', content: 'normal' }]);
|
||||
const answer = llm.chat([{ role: 'user', content: 'answer' }], { priority: 'high' });
|
||||
expect(await llm.chat([{ role: 'user', content: 'talk' }], { priority: 'low' })).toBeNull();
|
||||
await Promise.all([first, normal, answer]);
|
||||
expect(order).toEqual(['first', 'answer', 'normal']);
|
||||
expect(maxOpen).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,15 +3,23 @@
|
||||
*
|
||||
* - They show what they are doing: "생각 중…" while choosing a move and "입력 중…" while typing, for as long as a
|
||||
* person would take to type that line — then they send it and make the move ("채팅 치고 클릭").
|
||||
* - They talk in character (도발형·허세형·차분형·수다형·소심형, 존댓말/반말): a word with their own move, a reaction
|
||||
* to a person's move, answers when people chat, a greeting at the start and a word at the end.
|
||||
* - They talk in character (도발형·허세형·차분형·수다형·소심형, 존댓말/반말). A person who talks to a computer (by
|
||||
* name, by answering what it just said, or as the only computer at the table) always gets an answer within a few
|
||||
* seconds — the model's if it is quick, a built-in one if it is slow, busy or down (a flood is cut off).
|
||||
* - On their own they speak rarely and only about what just happened at this table (a big bet, someone folding,
|
||||
* 고/스톱…; never an ordinary move, never a greeting or small talk), with the move's meaning and the table's public
|
||||
* facts in the prompt. A line that contradicts the move ("풀 베팅이라니 쫄았네") or is about nothing in this game
|
||||
* is replaced with a built-in line made for that kind of move (acts.ts).
|
||||
* - Psychological choices go to the model: in 바퀴벌레 포커 it decides whether to tell the truth or bluff, and says
|
||||
* something to sell it. In 마피아 it says each line of the computer's plan in its own words.
|
||||
* Moves themselves still come from each game's computer strategy (it sees only its own screen). Without a model
|
||||
* (not configured, busy, down) the computers simply play as before, silently, and 마피아 uses its built-in lines.
|
||||
* Talking on their own is a room setting (`chatty`, off by default); 마피아 talks always because the game needs it.
|
||||
*/
|
||||
import { secureRandom } from '@bg/engine';
|
||||
import { botPace, hash01 } from '@bg/games/bots';
|
||||
import { botChatRequired } from '@bg/shared';
|
||||
import { cannedLine, contradicts, meaningOf, tableFacts, type ActMeaning } from './acts';
|
||||
import type { Llm } from './llm';
|
||||
import { cleanLine, decide, temperOf, writeLine, type LineRequest } from './lines';
|
||||
|
||||
@@ -31,27 +39,84 @@ export interface BrainRoom {
|
||||
recentChat(): { from: string; text: string }[];
|
||||
/** 똑똑한 편 (존댓말) or 허술한 편 (반말), docs/09 §9.1. */
|
||||
smart(bot: string): boolean;
|
||||
/**
|
||||
* The computers may chat on their own (room setting "컴퓨터 채팅"; always on in 마피아). Off: no small talk,
|
||||
* reactions, answers, greetings or end-of-game words — they just play (still showing "생각 중…").
|
||||
*/
|
||||
chatty(): boolean;
|
||||
now(): number;
|
||||
/** What `viewer` sees of the running game (public facts for the prompt); null outside a game. */
|
||||
view?(viewer: string): unknown;
|
||||
}
|
||||
|
||||
/** A few words for what someone just did (any game). */
|
||||
const ACTION_KO: Record<string, string> = {
|
||||
place: '돌을 놓음', move: '말을 움직임', MOVE: '말을 움직임', placeWall: '벽을 세움', castle: '캐슬링',
|
||||
play: '카드를 냄', discard: '패를 버림', DISCARD: '패를 버림', draw: '패를 가져옴', pass: '넘김', PASS: '넘김',
|
||||
call: '콜', check: '체크', die: '다이(포기)', half: '하프 베팅', quarter: '쿼터 베팅', ddadang: '따당', full: '풀 베팅',
|
||||
roll: '주사위를 굴림', hold: '주사위를 고정함', score: '점수를 적음', guess: '추리함', stop: '멈춤', continue: '계속 추리',
|
||||
offer: '카드를 건넴', peek: '카드를 몰래 봄', claim: '선언함', declare: '선언함', tsumo: '쯔모', ring: '종을 침',
|
||||
flip: '카드를 뒤집음', BUY: '땅을 삼', sell: '땅을 팖', THROW: '윷을 던짐', commit: '타일을 내려놓음', goStop: '고/스톱',
|
||||
respond: '대답함', resign: '기권', concede: '기권', CONCEDE: '기권', giveUp: '포기', choose: '골랐음', vote: '투표',
|
||||
};
|
||||
/** Talking on its own: at most one line per room every 40 s, and per computer every 90 s. */
|
||||
export const TALK_ROOM_GAP = 40_000;
|
||||
export const TALK_BOT_GAP = 90_000;
|
||||
/** A person keeps talking with the computer that answered them this long without naming it again (1 person rooms). */
|
||||
export const CONVERSATION_MS = 60_000;
|
||||
/** A line right after a computer's line is an answer to it. */
|
||||
const REPLY_MS = 20_000;
|
||||
/** Chance a computer reacts to a person's notable move (big bet, folding, 고, …) when it may talk. */
|
||||
const REACT_P = 0.3;
|
||||
/** How long an answer waits for the model before a built-in one is said instead. */
|
||||
export const ANSWER_WAIT_MS = 2500;
|
||||
/** A word about a move is dropped after this long (the game has moved on). */
|
||||
const TALK_WAIT_MS = 4000;
|
||||
/** Answers to one person: at most this many a minute (someone flooding a computer is not answered line by line). */
|
||||
export const ANSWERS_PER_MINUTE = 8;
|
||||
|
||||
/** Built-in answers (the model slow, busy, down, or its line unusable): by what the person said. */
|
||||
const QUICK_ANSWER: { test: RegExp; smart: string[]; casual: string[] }[] = [
|
||||
{ test: /안녕|ㅎㅇ|하이|반가/, smart: ['안녕하세요! 잘 부탁드려요.', '반가워요! 재밌게 해 봐요.'], casual: ['ㅎㅇ! 잘 해 보자 ㅋㅋ', '안녕~ 한 판 붙자!'] },
|
||||
{
|
||||
test: /뒤질|뒤져|죽을|죽여|쫄|겁|덤벼|이길\s?수|못\s?하|약하|ㅗ|ㅄ|\*{2,}/,
|
||||
smart: ['하하, 실력으로 답해 드릴게요.', '말보다 게임으로 보여 드릴게요.'],
|
||||
casual: ['ㅋㅋ 말로 하지 말고 게임으로 해!', '워워~ 판에서 보자 ㅋㅋ'],
|
||||
},
|
||||
{
|
||||
test: /\?|뭐|왜|누가|누구|어때|어떻게|몇|언제|할래|하냐|했냐|맞지|맞아/,
|
||||
smart: ['글쎄요, 두고 보시죠!', '음… 그건 비밀이에요.', '판이 끝나 보면 알겠죠?'],
|
||||
casual: ['ㅋㅋ 글쎄~ 두고 봐', '비밀이지롱~', '끝나 보면 알겠지 ㅋㅋ'],
|
||||
},
|
||||
{ test: /[\s\S]/, smart: ['하하, 그러게요.', '네, 계속 해 봐요!'], casual: ['ㅋㅋ 그치', 'ㅇㅋ 계속 가자!'] },
|
||||
];
|
||||
|
||||
/** Waits for `p` at most `ms` (real time): null after that. */
|
||||
function withDeadline<T>(p: Promise<T | null>, ms: number): Promise<T | null> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const late = new Promise<null>((r) => (timer = setTimeout(() => r(null), ms)));
|
||||
return Promise.race([p.catch(() => null), late]).finally(() => clearTimeout(timer));
|
||||
}
|
||||
|
||||
/** Words that tie a line to the game (a line on its own must mention the move, a player or one of these). */
|
||||
const GAME_WORDS = /판돈|베팅|칩|점수|\d+점|패|카드|돌|주사위|윷|족보|땅|타일|보석|차례|이번 판|한 판|수(?![가-힣])|여기|두면|둬|둔다|놓/;
|
||||
|
||||
const sleepReal = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
|
||||
|
||||
interface Happening {
|
||||
actor: string;
|
||||
meaning: ActMeaning;
|
||||
}
|
||||
|
||||
export class BotBrain {
|
||||
private lastRoomLine = -Infinity;
|
||||
private lastBotLine = new Map<string, number>();
|
||||
private happened: string[] = [];
|
||||
private happened: Happening[] = [];
|
||||
/** Showing "입력 중…". */
|
||||
private typing = new Set<string>();
|
||||
/** Writing or typing an answer, or typing a line: a new message to it waits in `pending`. */
|
||||
private busy = new Set<string>();
|
||||
/** The latest message to a busy computer, answered as soon as it is free. */
|
||||
private pending = new Map<string, { from: string; text: string; reply: boolean }>();
|
||||
/** Who each person is talking with. */
|
||||
private partner = new Map<string, { bot: string; at: number }>();
|
||||
private lastSpeaker: { bot: string; at: number } | null = null;
|
||||
/** When a person last chatted (a line after it is not an answer to a computer's earlier line). */
|
||||
private lastHumanChat = -Infinity;
|
||||
/** When each person was last answered (for the flood limit). */
|
||||
private answered = new Map<string, number[]>();
|
||||
/** The last built-in answer of each computer (not said twice in a row). */
|
||||
private lastQuick = new Map<string, string>();
|
||||
|
||||
constructor(
|
||||
private room: BrainRoom,
|
||||
@@ -65,27 +130,53 @@ export class BotBrain {
|
||||
return !!this.llm && this.llm.available() && this.room.playing() && this.room.humans().length > 0;
|
||||
}
|
||||
|
||||
/** How long `bot` takes to type `text` (each computer types at its own speed). */
|
||||
/** Games whose computers talk by their own plan (마피아, 라이어 게임): no small talk or answers from here. */
|
||||
private planned(): boolean {
|
||||
return botChatRequired(this.room.gameId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers to people work in and out of a game (lobby, result screen) while the computers sit in the room, and
|
||||
* without the model too (built-in answers): someone who talks to a computer is never left without a word.
|
||||
*/
|
||||
private canAnswer(): boolean {
|
||||
return this.room.chatty() && !this.planned() && this.room.humans().length > 0 && this.room.bots().length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* How long `bot` takes to type `text` (each computer types at its own speed): 8~16 characters a second, at least
|
||||
* 0.7 s and at most 3.5 s, so a short answer is up within 1~3 s of the question (the model's time counts toward it).
|
||||
*/
|
||||
typingMs(bot: string, text: string): number {
|
||||
const perChar = (120 + 90 * hash01(bot, 'typing')) * botPace(bot);
|
||||
return Math.round(Math.min(6500, Math.max(900, [...text].length * perChar)));
|
||||
const perChar = (60 + 40 * hash01(bot, 'typing')) * botPace(bot);
|
||||
return Math.round(Math.min(3500, Math.max(700, [...text].length * perChar)));
|
||||
}
|
||||
|
||||
thinking(bot: string, on: boolean): void {
|
||||
if (!this.typing.has(bot)) this.room.setActivity(bot, on ? 'thinking' : null);
|
||||
}
|
||||
|
||||
private showTyping(bot: string, on: boolean): void {
|
||||
if (on) this.typing.add(bot);
|
||||
else this.typing.delete(bot);
|
||||
this.room.setActivity(bot, on ? 'typing' : null);
|
||||
}
|
||||
|
||||
/** "입력 중…" for as long as typing takes, then `send` (skipped if the game ended meanwhile). */
|
||||
async type(bot: string, text: string, send: () => void, needPlaying = true): Promise<void> {
|
||||
this.typing.add(bot);
|
||||
this.room.setActivity(bot, 'typing');
|
||||
async type(bot: string, text: string, send: () => void, needPlaying = true, alreadyMs = 0): Promise<void> {
|
||||
this.busy.add(bot);
|
||||
this.showTyping(bot, true);
|
||||
try {
|
||||
await this.sleep(this.typingMs(bot, text));
|
||||
await this.sleep(Math.max(0, this.typingMs(bot, text) - alreadyMs));
|
||||
} finally {
|
||||
this.typing.delete(bot);
|
||||
this.room.setActivity(bot, null);
|
||||
this.showTyping(bot, false);
|
||||
this.busy.delete(bot);
|
||||
}
|
||||
if (!needPlaying || this.room.playing()) send();
|
||||
if (!needPlaying || this.room.playing()) {
|
||||
send();
|
||||
this.lastSpeaker = { bot, at: this.room.now() };
|
||||
}
|
||||
this.answerPending(bot);
|
||||
}
|
||||
|
||||
private request(bot: string, situation: string, task: string, extra: Partial<LineRequest> = {}): LineRequest {
|
||||
@@ -101,9 +192,10 @@ export class BotBrain {
|
||||
};
|
||||
}
|
||||
|
||||
private canTalk(bot: string, roomGap = 8000, botGap = 20_000): boolean {
|
||||
/** May talk on its own: rare (room and computer gaps) and never while busy. */
|
||||
private canTalk(bot: string): boolean {
|
||||
const now = this.room.now();
|
||||
return now - this.lastRoomLine >= roomGap && now - (this.lastBotLine.get(bot) ?? -Infinity) >= botGap && !this.typing.has(bot);
|
||||
return now - this.lastRoomLine >= TALK_ROOM_GAP && now - (this.lastBotLine.get(bot) ?? -Infinity) >= TALK_BOT_GAP && !this.busy.has(bot);
|
||||
}
|
||||
|
||||
private spoke(bot: string): void {
|
||||
@@ -112,30 +204,63 @@ export class BotBrain {
|
||||
this.lastBotLine.set(bot, now);
|
||||
}
|
||||
|
||||
private say(bot: string, line: string): Promise<void> {
|
||||
this.spoke(bot);
|
||||
return this.type(bot, line, () => this.room.roomChat(bot, line));
|
||||
}
|
||||
|
||||
private situation(): string {
|
||||
/** What is going on, as facts: the last moves with what they mean, and the table (칩·점수·카드 수). */
|
||||
private situation(bot: string): string {
|
||||
const parts: string[] = [];
|
||||
const last = this.happened.slice(-4);
|
||||
return last.length ? `최근: ${last.join(', ')}` : '게임이 막 시작됐다';
|
||||
if (last.length) {
|
||||
const said = last.map((h, i) => `${this.room.nameOf(h.actor)}${h.actor === bot ? '(나)' : ''}: ${h.meaning.ko}${i === last.length - 1 && h.meaning.mean ? ` — ${h.meaning.mean}` : ''}`);
|
||||
parts.push(`방금 일어난 일(오래된 것부터): ${said.join(' / ')}`);
|
||||
} else parts.push('게임이 막 시작됐다');
|
||||
let view: unknown = null;
|
||||
try {
|
||||
view = this.room.view?.(bot) ?? null;
|
||||
} catch {
|
||||
view = null;
|
||||
}
|
||||
const facts = tableFacts(view, bot, (id) => this.room.nameOf(id));
|
||||
if (facts.length) parts.push(`지금 판: ${facts.join(' / ')}`);
|
||||
return parts.join('\n');
|
||||
}
|
||||
|
||||
/** Someone played: remembered for the computers' sense of the game; now and then a computer reacts to a person. */
|
||||
/** Move names that came up just before (a line may mention those). */
|
||||
private known(): string[] {
|
||||
return this.happened.slice(-3).map((h) => h.meaning.ko);
|
||||
}
|
||||
|
||||
/** A line said on its own must be about this game: the move, a player, or a game word. */
|
||||
private relevant(line: string, meaning: ActMeaning | null, people: string[]): boolean {
|
||||
if (GAME_WORDS.test(line)) return true;
|
||||
if (people.some((p) => p && (line.includes(p) || line.includes(p.replace(/\s/g, ''))))) return true;
|
||||
// "카드를 뒤집음" → 카드, 뒤집; a stem shorter than two letters is not used ("다이" → "다" would match "다들").
|
||||
const stems = (meaning?.ko ?? '').split(' ').map((w) => {
|
||||
const stem = w.replace(/(을|를|이|가|은|는|음|함)$/, '');
|
||||
return stem.length >= 2 ? stem : w;
|
||||
});
|
||||
return stems.some((w) => line.includes(w));
|
||||
}
|
||||
|
||||
/** Someone played: remembered for the computers' sense of the game; a notable move by a person may get a word. */
|
||||
onAction(actor: string, action: unknown): void {
|
||||
const type = String((action as { type?: string } | null)?.type ?? '');
|
||||
if (!type || type === 'chat' || type === 'say' || type === 'reaction' || type === 'ping' || type === 'timeout') return;
|
||||
this.happened.push(`${this.room.nameOf(actor)} ${ACTION_KO[type] ?? '행동함'}`);
|
||||
const meaning = meaningOf(this.room.gameId(), action);
|
||||
this.happened.push({ actor, meaning });
|
||||
if (this.happened.length > 12) this.happened.shift();
|
||||
if (!this.enabled() || this.room.bots().includes(actor) || this.room.gameId() === 'mafia') return;
|
||||
const bots = this.room.bots().filter((b) => this.canTalk(b, 10_000, 30_000));
|
||||
if (!bots.length || this.random() > 0.12) return;
|
||||
if (!meaning.notable || !this.enabled() || !this.room.chatty() || this.room.bots().includes(actor) || this.planned()) return;
|
||||
const bots = this.room.bots().filter((b) => this.canTalk(b));
|
||||
if (!bots.length || this.random() > REACT_P) return;
|
||||
const bot = bots[Math.floor(this.random() * bots.length)]!;
|
||||
this.spoke(bot);
|
||||
const who = this.room.nameOf(actor);
|
||||
void writeLine(this.llm, this.request(bot, this.situation(), `${who}이(가) 방금 ${ACTION_KO[type] ?? '수를 뒀다'}. ${who}에게 반응하는 한마디(놀리거나 떠보기).`)).then((line) => {
|
||||
if (line) return this.type(bot, line, () => this.room.roomChat(bot, line));
|
||||
const known = this.known();
|
||||
const task = `${who}이(가) 방금 "${meaning.ko}"를 했다${meaning.mean ? `(${meaning.mean})` : ''}. 그 뜻에 맞게 ${who}에게 반응하는 한마디(떠보거나 장난스럽게 받아치기).`;
|
||||
void writeLine(this.llm, this.request(bot, this.situation(bot), task, { maxLen: 36, priority: 'low', timeoutMs: TALK_WAIT_MS })).then((raw) => {
|
||||
let line = raw;
|
||||
// Contradicting the move, or about nothing in this game: a built-in line made for this kind of move instead.
|
||||
if (line && (contradicts(line, meaning, false, known) || !this.relevant(line, meaning, [who]))) line = null;
|
||||
line ??= cannedLine(meaning, who, this.room.smart(bot), false, this.random);
|
||||
if (line && !this.busy.has(bot) && this.room.playing()) return this.type(bot, line, () => this.room.roomChat(bot, line!));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -148,18 +273,28 @@ export class BotBrain {
|
||||
let act = action;
|
||||
let line: string | null = null;
|
||||
const a = action as { type?: string; claim?: string; cardId?: string; to?: string };
|
||||
const meaning = meaningOf(this.room.gameId(), action);
|
||||
if (this.room.gameId() === 'cockroach-poker' && (a.type === 'offer' || a.type === 'pass') && a.claim) {
|
||||
const r = await this.cockroachBluff(bot, a, view);
|
||||
if (r) {
|
||||
act = r.action;
|
||||
line = r.say;
|
||||
// Chat off: the model still decides truth or bluff, the computer just hands the card over without a word.
|
||||
line = this.room.chatty() ? r.say : null;
|
||||
}
|
||||
} else if (this.canTalk(bot) && this.random() < temperOf(bot).talk) {
|
||||
const type = String(a.type ?? '');
|
||||
line = await writeLine(this.llm, this.request(bot, this.situation(), `나는 지금 "${ACTION_KO[type] ?? '내 수'}"를 하려 한다. 이 수를 두며 상대에게 던지는 도발이나 심리전 한마디.`));
|
||||
} else if (meaning.notable && this.room.chatty() && !this.planned() && this.canTalk(bot) && this.random() < temperOf(bot).talk) {
|
||||
// Only a notable move of its own (a big bet, 다이, 고…) gets a word; ordinary moves are played in silence.
|
||||
this.spoke(bot);
|
||||
const known = this.known();
|
||||
const others = this.room.humans().map((h) => this.room.nameOf(h));
|
||||
const task = `나는 지금 "${meaning.ko}"를 하려 한다${meaning.mean ? `(${meaning.mean})` : ''}. 이 수에 맞게 상대에게 던지는 도발이나 심리전 한마디.`;
|
||||
line = await writeLine(this.llm, this.request(bot, this.situation(bot), task, { maxLen: 36, priority: 'low', timeoutMs: TALK_WAIT_MS }));
|
||||
if (line && (contradicts(line, meaning, true, known) || !this.relevant(line, meaning, others))) line = null;
|
||||
line ??= cannedLine(meaning, this.room.nameOf(bot), this.room.smart(bot), true, this.random);
|
||||
}
|
||||
if (line && this.room.playing()) {
|
||||
await this.say(bot, line);
|
||||
if (line && this.room.playing() && !this.busy.has(bot)) {
|
||||
this.spoke(bot);
|
||||
const said = line;
|
||||
await this.type(bot, said, () => this.room.roomChat(bot, said));
|
||||
await this.sleep(Math.round((300 + 500 * this.random()) * botPace(bot)));
|
||||
}
|
||||
return act;
|
||||
@@ -193,47 +328,123 @@ export class BotBrain {
|
||||
return { action: { ...a, claim }, say };
|
||||
}
|
||||
|
||||
/** People chatting: a named computer answers; otherwise sometimes one of them joins in. */
|
||||
onHumanChat(from: string, text: string): void {
|
||||
if (!this.enabled() || this.room.gameId() === 'mafia') return;
|
||||
/**
|
||||
* The computer a person is talking to: named ("컴퓨터 1", "컴1", "1번", or its full name), or answering what a
|
||||
* computer just said (no one else spoke since), or — with one person in the room — the computer they were talking
|
||||
* with a moment ago or the only computer there.
|
||||
*/
|
||||
private addressee(from: string, text: string, prevHumanChat: number): { bot: string; reply: boolean } | undefined {
|
||||
const bots = this.room.bots();
|
||||
const flat = text.replace(/\s/g, '');
|
||||
const named = bots.find((b) => {
|
||||
const n = /^컴퓨터 (\d+)$/.exec(this.room.nameOf(b))?.[1];
|
||||
return n ? new RegExp(`(컴퓨터\\s?${n}|컴${n}|(?<![0-9])${n}번)(?![0-9])`).test(text) : false;
|
||||
});
|
||||
const bot = named ?? (this.random() < 0.4 ? bots[Math.floor(this.random() * bots.length)] : undefined);
|
||||
if (!bot || this.typing.has(bot)) return;
|
||||
this.spoke(bot);
|
||||
const who = this.room.nameOf(from);
|
||||
void writeLine(this.llm, this.request(bot, this.situation(), `${who}이(가) 채팅으로 "${text.slice(0, 100)}"라고 했다. 같이 게임하는 사람으로서 대답한다. 질문이면 그 질문에 직접 답하고(성격대로, 허세·도발·엄살 가능), 질문이 아니면 맞장구치거나 받아친다.`)).then((line) => {
|
||||
if (line) return this.type(bot, line, () => this.room.roomChat(bot, line));
|
||||
const name = this.room.nameOf(b);
|
||||
const n = /^컴퓨터 (\d+)$/.exec(name)?.[1];
|
||||
if (n) return new RegExp(`(컴퓨터\\s?${n}|컴${n}|(?<![0-9])${n}번)(?![0-9])`).test(text);
|
||||
return name.length >= 2 && flat.includes(name.replace(/\s/g, ''));
|
||||
});
|
||||
if (named) return { bot: named, reply: false };
|
||||
const now = this.room.now();
|
||||
const alone = this.room.humans().length === 1;
|
||||
const partner = this.partner.get(from);
|
||||
if (alone && partner && now - partner.at <= CONVERSATION_MS && bots.includes(partner.bot)) return { bot: partner.bot, reply: false };
|
||||
const last = this.lastSpeaker;
|
||||
if (last && last.at >= prevHumanChat && now - last.at <= REPLY_MS && bots.includes(last.bot)) return { bot: last.bot, reply: true };
|
||||
if (alone && bots.length === 1) return { bot: bots[0]!, reply: false };
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** At most `ANSWERS_PER_MINUTE` answers a minute to one person. */
|
||||
private mayAnswer(from: string): boolean {
|
||||
const now = this.room.now();
|
||||
const recent = (this.answered.get(from) ?? []).filter((t) => now - t < 60_000);
|
||||
this.answered.set(from, recent);
|
||||
return recent.length < ANSWERS_PER_MINUTE;
|
||||
}
|
||||
|
||||
/**
|
||||
* People chatting: a computer spoken to always answers (right after the line it is typing, if any). People
|
||||
* talking among themselves are left alone.
|
||||
*/
|
||||
onHumanChat(from: string, text: string): void {
|
||||
const prev = this.lastHumanChat;
|
||||
this.lastHumanChat = this.room.now();
|
||||
if (!this.canAnswer()) return;
|
||||
const to = this.addressee(from, text, prev);
|
||||
if (!to || !this.mayAnswer(from)) return;
|
||||
const { bot, reply } = to;
|
||||
this.partner.set(from, { bot, at: this.room.now() });
|
||||
// Busy: the newest message waits and is answered right after (a burst of lines gets one answer, not none).
|
||||
if (this.busy.has(bot)) this.pending.set(bot, { from, text, reply });
|
||||
else void this.answer(bot, from, text, reply);
|
||||
}
|
||||
|
||||
private answerPending(bot: string): void {
|
||||
const next = this.pending.get(bot);
|
||||
if (!next) return;
|
||||
this.pending.delete(bot);
|
||||
if (this.canAnswer()) void this.answer(bot, next.from, next.text, next.reply);
|
||||
}
|
||||
|
||||
/** A built-in answer that fits what the person said (a greeting, a jab, a question), not the same twice in a row. */
|
||||
quickAnswer(bot: string, text: string): string {
|
||||
const kind = QUICK_ANSWER.find((q) => q.test.test(text))!;
|
||||
const pool = kind[this.room.smart(bot) ? 'smart' : 'casual'].filter((l) => l !== this.lastQuick.get(bot));
|
||||
const line = pool[Math.floor(this.random() * pool.length) % pool.length]!;
|
||||
this.lastQuick.set(bot, line);
|
||||
return line;
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers a person at once: "입력 중…" shows while the model writes (that time counts as typing), then the line.
|
||||
* The model gets `ANSWER_WAIT_MS`; slow, busy, down or unusable, a built-in answer is said instead.
|
||||
*/
|
||||
private async answer(bot: string, from: string, text: string, reply = false): Promise<void> {
|
||||
this.busy.add(bot);
|
||||
this.showTyping(bot, true);
|
||||
this.answered.set(from, [...(this.answered.get(from) ?? []), this.room.now()]);
|
||||
const t0 = this.room.now();
|
||||
let line: string | null = null;
|
||||
if (this.llm?.available()) {
|
||||
const who = this.room.nameOf(from);
|
||||
const task =
|
||||
`${who}이(가) 나(${this.room.nameOf(bot)})에게 채팅으로 "${text.slice(0, 100)}"라고 했다. ${who}에게 바로 대답한다. ` +
|
||||
'질문이면 그 질문에 직접 답하고(성격대로, 허세·도발·엄살 가능, 판 상황에 근거해서), 질문이 아니면 맞장구치거나 받아친다. 짧게.';
|
||||
try {
|
||||
line = await withDeadline(writeLine(this.llm, this.request(bot, this.situation(bot), task, { maxLen: 34, priority: 'high' })), ANSWER_WAIT_MS);
|
||||
} catch {
|
||||
line = null;
|
||||
}
|
||||
}
|
||||
line ??= this.quickAnswer(bot, text);
|
||||
this.busy.delete(bot);
|
||||
const said = line;
|
||||
// Sent in or out of a game (the person asked); the model's time already counted as typing.
|
||||
await this.type(bot, said, () => this.room.roomChat(bot, said), false, this.room.now() - t0);
|
||||
this.partner.set(from, { bot, at: this.room.now() });
|
||||
// An answer to an unnamed reply does not invite the next line in turn: people talking among themselves after
|
||||
// it are left alone (otherwise the computer would answer every line between two people forever).
|
||||
if (reply && this.lastSpeaker?.bot === bot) this.lastSpeaker = null;
|
||||
}
|
||||
|
||||
onGameStart(): void {
|
||||
this.happened = [];
|
||||
// A game with computers and people: make sure the model is loaded before anyone talks.
|
||||
if (this.llm?.available() && this.room.humans().length && this.room.bots().length) void this.llm.warm();
|
||||
if (!this.enabled() || this.room.gameId() === 'mafia' || this.random() > 0.7) return;
|
||||
const bots = this.room.bots();
|
||||
const bot = bots[Math.floor(this.random() * bots.length)];
|
||||
if (!bot) return;
|
||||
this.spoke(bot);
|
||||
void writeLine(this.llm, this.request(bot, '게임이 막 시작됐다', '시작 인사 겸 가벼운 선전포고 한마디.')).then((line) => {
|
||||
if (line) return this.type(bot, line, () => this.room.roomChat(bot, line));
|
||||
});
|
||||
// A game with computers and people where the model will be used: make sure it is loaded before anyone talks.
|
||||
// No greeting: the computers speak on their own only about what happens in the game.
|
||||
const usesModel = this.room.chatty() || this.room.gameId() === 'cockroach-poker';
|
||||
if (usesModel && this.llm?.available() && this.room.humans().length && this.room.bots().length) void this.llm.warm();
|
||||
}
|
||||
|
||||
/** The game ended: a computer that won gloats a little, or one that lost takes it with a word. */
|
||||
onGameEnd(ranking: string[][]): void {
|
||||
if (!this.llm?.available() || !this.room.humans().length || this.room.gameId() === 'mafia' || this.random() > 0.85) return;
|
||||
if (!this.llm?.available() || !this.room.chatty() || !this.room.humans().length || this.planned() || this.random() > 0.6) return;
|
||||
const bots = this.room.bots();
|
||||
const winner = (ranking[0] ?? []).find((p) => bots.includes(p));
|
||||
const bot = winner ?? bots[Math.floor(this.random() * bots.length)];
|
||||
if (!bot) return;
|
||||
const task = winner ? '내가 이겼다. 상대를 살짝 놀리며 이긴 소감 한마디(한 판 더 하자고 해도 좋다).' : '내가 졌다. 아쉬워하며 다음엔 이기겠다는 한마디.';
|
||||
void writeLine(this.llm, this.request(bot, '게임이 끝났다', task)).then((line) => {
|
||||
if (line) return this.type(bot, line, () => this.room.roomChat(bot, line), false);
|
||||
const first = (ranking[0] ?? []).map((p) => this.room.nameOf(p)).join(', ');
|
||||
const task = winner ? '내가 이겼다. 상대를 살짝 놀리며 이긴 소감 한마디(한 판 더 하자고 해도 좋다).' : `내가 졌다(1등: ${first}). 아쉬워하며 다음엔 이기겠다는 한마디.`;
|
||||
void writeLine(this.llm, this.request(bot, `게임이 끝났다. 1등: ${first}`, task, { priority: 'low' })).then((line) => {
|
||||
if (line && !this.busy.has(bot)) return this.type(bot, line, () => this.room.roomChat(bot, line), false);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -39,7 +39,10 @@ export function systemPrompt(bot: string, name: string, maxLen: number, smart: b
|
||||
`성격: ${t.ko} — ${t.desc}`,
|
||||
`말투: ${speechOf(smart)}.`,
|
||||
`규칙: 한국어 채팅 한 줄만 쓴다. ${maxLen}자 이내. 대사만 쓰고 따옴표·설명·괄호·영어·한자는 쓰지 않는다.`,
|
||||
'욕설, 비하, 외모·성별·나이 언급, 개인정보, 링크는 절대 쓰지 않는다. 게임과 상관없는 이야기는 하지 않는다.',
|
||||
'욕설·막말·깔보는 호칭, 비하, 외모·성별·나이 언급, 개인정보, 링크는 절대 쓰지 않는다. 상대가 거친 말을 해도 장난스럽게 받아넘긴다.',
|
||||
'"상황"에 적힌 사실에만 근거해서 말한다. 적히지 않은 점수·패·행동은 지어내지 않고, 게임과 상관없는 혼잣말이나 "다들 준비됐냐" 같은 뻔한 말은 하지 않는다.',
|
||||
'최근 채팅에서 "(나)"가 붙은 줄은 내가 한 말이다. 내가 했던 말의 시작이나 표현을 되풀이하지 않는다.',
|
||||
'누가 한 수의 뜻이 적혀 있으면 그 뜻에 맞게 말한다(센 베팅을 한 사람에게 겁먹었다고 하지 않고, 포기한 사람에게 세게 나왔다고 하지 않는다).',
|
||||
'자신이 AI나 프로그램이라고 말하지 않는다. 숨겨진 정보(내 패, 내 카드, 내 직업)는 절대 밝히지 않는다.',
|
||||
].join('\n');
|
||||
}
|
||||
@@ -61,10 +64,21 @@ export interface LineRequest {
|
||||
maxLen?: number;
|
||||
/** Extra patterns the line must not contain (e.g. a mafia computer saying it is mafia). */
|
||||
forbid?: RegExp[];
|
||||
/** answer = a person spoke to it (goes ahead of everything); talk = on its own (dropped when the model is busy). */
|
||||
priority?: 'high' | 'normal' | 'low';
|
||||
/** Give up on the model after this long (a word about a move is no use once the game has moved on). */
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
const AI_WORDS = /인공\s*지능|\bAI\b|챗봇|언어\s*모델|어시스턴트|프로그램입니다|GPT|모델로서/i;
|
||||
const FOREIGN = /[一-鿿-ヿ]|[A-Za-z]{4,}/;
|
||||
/**
|
||||
* Rude words the shared kid-safe filter lets through but the model likes to use when it plays "도발형" or is sworn at
|
||||
* ("망할 놈", "닥쳐", "뒤져라", "꼬맹이" — all seen from gemma3:4b in testing).
|
||||
*/
|
||||
const RUDE = /뒤지겠|뒤지게|놈|(이|저|그|미친)\s?년|새끼|지랄|닥치|닥쳐|꺼져|뒤질|뒤져|죽을래|죽여|죽인다|팰\s?거|때려|병신|멍청|바보|어리석|꼬맹|찐따|빌어먹|망할|씹|좆|미친|븅|등신|한심/;
|
||||
/** The model repeating its instructions instead of talking ("철수이(가) 채팅으로 … 라고 했다"). */
|
||||
const ECHO = /이\(가\)|채팅으로|라고 했다|할 말:|상황:|최근 채팅/;
|
||||
|
||||
/** One clean chat line out of whatever the model wrote, or null when nothing usable is left. */
|
||||
export function cleanLine(raw: string, maxLen = 40, forbid: RegExp[] = []): string | null {
|
||||
@@ -79,7 +93,7 @@ export function cleanLine(raw: string, maxLen = 40, forbid: RegExp[] = []): stri
|
||||
.replace(/[*_#>]/g, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
if (!line || FOREIGN.test(line) || AI_WORDS.test(line)) return null;
|
||||
if (!line || FOREIGN.test(line) || AI_WORDS.test(line) || RUDE.test(line) || ECHO.test(line)) return null;
|
||||
if ([...line].length > maxLen) {
|
||||
const chars = [...line];
|
||||
const cut = chars.slice(0, maxLen).join('');
|
||||
@@ -98,14 +112,15 @@ export async function writeLine(llm: Llm | null, req: LineRequest): Promise<stri
|
||||
if (!llm || !llm.available()) return null;
|
||||
const maxLen = req.maxLen ?? 40;
|
||||
const parts = [`게임: ${req.game}`, `상황: ${req.situation}`];
|
||||
if (req.recent?.length) parts.push(`최근 채팅:\n${req.recent.slice(-8).map((m) => `${m.from}: ${m.text}`).join('\n')}`);
|
||||
if (req.recent?.length) parts.push(`최근 채팅:\n${req.recent.slice(-8).map((m) => `${m.from}${m.from === req.name ? '(나)' : ''}: ${m.text}`).join('\n')}`);
|
||||
if (req.example) parts.push(`예시(뜻은 같게, 표현은 너답게 새로): ${req.example}`);
|
||||
parts.push(`할 말: ${req.task}`);
|
||||
const messages: LlmMessage[] = [
|
||||
{ role: 'system', content: systemPrompt(req.bot, req.name, maxLen, req.smart) },
|
||||
{ role: 'user', content: parts.join('\n') },
|
||||
];
|
||||
const raw = await llm.chat(messages, { maxTokens: 70, temperature: 0.95 });
|
||||
// One line of at most ~40 Korean characters is 15~30 tokens; stop at the first newline.
|
||||
const raw = await llm.chat(messages, { maxTokens: 56, temperature: 0.9, stop: ['\n'], priority: req.priority ?? 'normal', ...(req.timeoutMs ? { timeoutMs: req.timeoutMs } : {}) });
|
||||
return raw === null ? null : cleanLine(raw, maxLen, req.forbid);
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,10 @@ export interface LlmConfig {
|
||||
/** Ollama base URL, e.g. http://192.168.10.9:11434. */
|
||||
url: string;
|
||||
model: string;
|
||||
/** Requests running at once (one GPU). */
|
||||
/**
|
||||
* Requests sent at once. Default 1: Ollama on the one GPU runs one request at a time (`n_slots = 1`), so a second
|
||||
* one would only wait inside Ollama — where an answer to a person could not get ahead of small talk.
|
||||
*/
|
||||
maxConcurrent?: number;
|
||||
/** Requests allowed to wait; more are refused at once (the caller uses a built-in line). */
|
||||
maxQueue?: number;
|
||||
@@ -39,7 +42,7 @@ export interface LlmStats {
|
||||
|
||||
export class Llm {
|
||||
private running = 0;
|
||||
private waiting: (() => void)[] = [];
|
||||
private waiting: { go: () => void; high: boolean }[] = [];
|
||||
private totalMs = 0;
|
||||
private backoffUntil = 0;
|
||||
private failures = 0;
|
||||
@@ -60,17 +63,31 @@ export class Llm {
|
||||
|
||||
/**
|
||||
* One chat completion. `format` is a JSON schema for structured answers. Returns the text, or null when it could
|
||||
* not be had in time (busy, down, timeout).
|
||||
* not be had in time (busy, down, timeout). `priority`: `high` (answering a person) goes ahead of everything that
|
||||
* waits; `low` (small talk nobody asked for) is dropped at once when the model is busy, so it never delays the rest.
|
||||
* `stop` ends the answer early (one chat line: a newline).
|
||||
*/
|
||||
async chat(messages: LlmMessage[], opts: { maxTokens?: number; temperature?: number; format?: object; timeoutMs?: number } = {}): Promise<string | null> {
|
||||
async chat(
|
||||
messages: LlmMessage[],
|
||||
opts: { maxTokens?: number; temperature?: number; format?: object; timeoutMs?: number; priority?: 'high' | 'normal' | 'low'; stop?: string[] } = {},
|
||||
): Promise<string | null> {
|
||||
this.stats.requests++;
|
||||
const full = this.running >= (this.cfg.maxConcurrent ?? 2) && this.waiting.length >= (this.cfg.maxQueue ?? 6);
|
||||
if (!this.available() || full) {
|
||||
const max = this.cfg.maxConcurrent ?? 1;
|
||||
const busy = this.running >= max;
|
||||
const full = busy && this.waiting.length >= (this.cfg.maxQueue ?? 6) && opts.priority !== 'high';
|
||||
if (!this.available() || full || (busy && opts.priority === 'low')) {
|
||||
this.stats.skipped++;
|
||||
return null;
|
||||
}
|
||||
if (this.running >= (this.cfg.maxConcurrent ?? 2)) await new Promise<void>((r) => this.waiting.push(r));
|
||||
this.running++;
|
||||
if (busy) {
|
||||
await new Promise<void>((go) => {
|
||||
const high = opts.priority === 'high';
|
||||
// Answers wait only behind earlier answers.
|
||||
const at = high ? this.waiting.findIndex((w) => !w.high) : -1;
|
||||
if (at >= 0) this.waiting.splice(at, 0, { go, high });
|
||||
else this.waiting.push({ go, high });
|
||||
});
|
||||
} else this.running++; // a waiter is handed the finished request's place (`running` stays)
|
||||
const t0 = this.now();
|
||||
const ctl = new AbortController();
|
||||
const timer = setTimeout(() => ctl.abort(), opts.timeoutMs ?? this.cfg.timeoutMs ?? 6000);
|
||||
@@ -85,7 +102,7 @@ export class Llm {
|
||||
stream: false,
|
||||
keep_alive: this.cfg.keepAlive ?? '2h',
|
||||
...(opts.format ? { format: opts.format } : {}),
|
||||
options: { temperature: opts.temperature ?? 0.9, num_predict: opts.maxTokens ?? 80 },
|
||||
options: { temperature: opts.temperature ?? 0.9, num_predict: opts.maxTokens ?? 80, ...(opts.stop ? { stop: opts.stop } : {}) },
|
||||
}),
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
@@ -110,8 +127,9 @@ export class Llm {
|
||||
return null;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
this.running--;
|
||||
this.waiting.shift()?.();
|
||||
const next = this.waiting.shift();
|
||||
if (next) next.go();
|
||||
else this.running--;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
134
apps/server/src/rooms/apple.room.test.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
/** 사과 게임 through a real Room: a practice race against a computer to the end, the server clock, away players (docs/games/apple.md §8.5, §13). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { findMoves, type AppleState, type AppleView } from '@bg/games/apple';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const store = new RoomStore(openDb(':memory:'));
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
return { clock, manager, conn };
|
||||
}
|
||||
|
||||
const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract<ServerMessage, { t: 'state' }>).view as AppleView;
|
||||
|
||||
describe('사과 게임 room flow', () => {
|
||||
test('컴퓨터와 연습: 사람은 화면에 보이는 판으로 합 10을 지우고, 컴퓨터도 자기 판을 풀고, 2분 뒤 서버 시계로 끝나요', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'apple') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bot = room.game!.players.find(isBotId)!;
|
||||
expect(bot).toBeDefined();
|
||||
let cs = 0;
|
||||
let rejects = 0;
|
||||
for (let i = 0; i < 4 * 200 && !room.game!.finished; i++) {
|
||||
h.clock.advance(250);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
// The person clears one rectangle every 2 seconds, read from their own screen.
|
||||
const v = lastView(a);
|
||||
if (i % 8 === 0 && v.phase === 'playing' && v.cells) {
|
||||
const m = findMoves(v.cells, 1)[0];
|
||||
if (m) room.act('A', ++cs, { type: 'select', ...m });
|
||||
}
|
||||
rejects = a.msgs.filter((m) => m.t === 'reject').length;
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(rejects).toBe(0);
|
||||
const s = room.game!.state as AppleState;
|
||||
expect(s.final!.endReason === 'time' || s.final!.endReason === 'cleared').toBe(true);
|
||||
expect(s.score.A).toBeGreaterThan(20);
|
||||
expect(s.score[bot]).toBeGreaterThan(10);
|
||||
// My view never carried the computer's board.
|
||||
expect(JSON.stringify(lastView(a))).not.toContain(s.boards[bot]!);
|
||||
expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort());
|
||||
});
|
||||
|
||||
test('합이 10이 아닌 직사각형은 거절(벌점 없음), 연결이 끊긴 사람은 일찍 시간 초과되지 않아요', () => {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'apple', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
const b = h.conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.ready('B', true);
|
||||
expect(room.start('A')).toBeNull();
|
||||
h.clock.advance(3000);
|
||||
room.onTimer();
|
||||
const s = () => room.game!.state as AppleState;
|
||||
expect(s().phase).toBe('playing');
|
||||
// Find a 2-cell rectangle that does not add up to 10.
|
||||
const cells = s().boards.A!;
|
||||
const c = [...Array(16).keys()].find((k) => Number(cells[k]) + Number(cells[k + 1]) !== 10)!;
|
||||
room.act('A', 1, { type: 'select', r0: 0, c0: c, r1: 0, c1: c + 1 });
|
||||
const rej = a.msgs.filter((m) => m.t === 'reject').at(-1) as { reason: string };
|
||||
expect(rej.reason).toMatch(/^합이 \d+이에요/);
|
||||
expect(s().score.A).toBe(0);
|
||||
// B drops off: 70 s later (past the 60 s grace) nothing happened to B, the race goes on.
|
||||
room.disconnect(b);
|
||||
expect(room.effectiveDeadline()).toBe(s().endsAt);
|
||||
h.clock.advance(70_000);
|
||||
room.onTimer();
|
||||
expect(s().phase).toBe('playing');
|
||||
expect(s().status.B).toBe('playing');
|
||||
h.clock.advance(s().endsAt! - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
});
|
||||
test('제한 시간 무제한: 타이머가 돌지 않고, 끊긴 사람은 유예 뒤 한 번만 여기까지 처리(바쁜 루프 없음), 남은 사람이 여기까지 하면 끝', () => {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'apple', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
const b = h.conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.ready('B', true);
|
||||
expect(room.configure('A', { options: { timeLimitSec: null } })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
h.clock.advance(3000);
|
||||
room.onTimer();
|
||||
const s = () => room.game!.state as AppleState;
|
||||
expect(s().phase).toBe('playing');
|
||||
expect(s().endsAt).toBeNull();
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.disconnect(b);
|
||||
const d = room.effectiveDeadline()!;
|
||||
expect(d).toBeGreaterThan(h.clock.now());
|
||||
h.clock.advance(d - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('done');
|
||||
expect(s().status.A).toBe('playing');
|
||||
// Nothing else is due: no timer fires again for B.
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.act('A', 1, { type: 'stop' });
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(s().final!.summary).toContain('모두 끝냈어요');
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -159,7 +203,8 @@ export class BotDriver {
|
||||
let decision: { action: unknown; next: number; hint?: string } = { action: null, next: 3000 };
|
||||
const t0 = performance.now();
|
||||
try {
|
||||
decision = strategy({ me: bot, view: structuredClone(def.view(g.state, bot)), now, random: this.random, persona: botPersona(bot, this.room.profile?.(bot).base), names, memory });
|
||||
const profile = this.room.profile?.(bot);
|
||||
decision = strategy({ me: bot, view: structuredClone(def.view(g.state, bot)), now, random: this.random, persona: botPersona(bot, profile?.base), level: profile?.level ?? idLevel(bot), names, memory });
|
||||
} catch (err) {
|
||||
this.room.log?.('error', 'bot decision failed', { game: def.id, err: String(err) });
|
||||
}
|
||||
@@ -218,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 };
|
||||
}
|
||||
@@ -238,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;
|
||||
@@ -257,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;
|
||||
|
||||
@@ -10,7 +10,7 @@ import { RoomStore } from './store';
|
||||
type Msgs = ServerMessage[];
|
||||
type StateMsg = Extract<ServerMessage, { t: 'state' }>;
|
||||
|
||||
function harness(players: string[]) {
|
||||
function harness(players: string[], options: Record<string, unknown> = {}) {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
@@ -19,7 +19,7 @@ function harness(players: string[]) {
|
||||
const deps = { store, games, users: { publicUser: (id: string) => ({ id, nickname: id, avatar: null, kind: 'guest' as const }) }, now: clock.now };
|
||||
const config: RoomConfig = {
|
||||
gameId: 'catchmind',
|
||||
options: games.catchmind.defaultOptions,
|
||||
options: { ...games.catchmind.defaultOptions, ...options },
|
||||
maxPlayers: players.length,
|
||||
visibility: 'private',
|
||||
allowSpectators: true,
|
||||
@@ -170,12 +170,29 @@ describe('그림 맞히기 room flow', () => {
|
||||
expect(state().away).toEqual([d]);
|
||||
});
|
||||
|
||||
test('그리기 무제한: 연결된 출제자는 타이머 없음, 연결이 끊기면 10초 뒤 턴 종료', () => {
|
||||
const { room, clock, conns, state, act } = harness(['A', 'B'], { drawSeconds: null, hints: 'basic' });
|
||||
const d = state().turn.drawer;
|
||||
act(d, { type: 'chooseWord', index: 0 });
|
||||
expect(state().turn.endsAt).toBeNull();
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
clock.advance(600_000);
|
||||
expect(state().turn.phase).toBe('drawing');
|
||||
room.disconnect(conns[d]!);
|
||||
room.clearTimer();
|
||||
expect(room.effectiveDeadline()).toBe(clock.now() + 10_000);
|
||||
clock.advance(10_000);
|
||||
room.onTimer();
|
||||
room.clearTimer();
|
||||
expect(state().turn.endReason).toBe('drawerAway');
|
||||
});
|
||||
|
||||
test('연결된 출제자는 힌트·시간 만료 때만 tick(10초 지나도 끝나지 않음)', () => {
|
||||
const { room, clock, state, act } = harness(['A', 'B']);
|
||||
const d = state().turn.drawer;
|
||||
act(d, { type: 'chooseWord', index: 0 });
|
||||
const t0 = state().turn.startedAt;
|
||||
const ends = state().turn.endsAt;
|
||||
const ends = state().turn.endsAt!;
|
||||
expect(room.effectiveDeadline()).toBe(t0 + (ends - t0) / 2);
|
||||
clock.advance(20_000);
|
||||
room.onTimer();
|
||||
|
||||
130
apps/server/src/rooms/liar.room.test.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
/**
|
||||
* 라이어 게임 through a real Room with computers: one person and computers play a whole game with the real bot driver
|
||||
* and the room clock. The person's connection never learns the word (when they are the liar) or who the liar is (when
|
||||
* they are a citizen) before the reveal, and the room chat stays closed while the game runs.
|
||||
*/
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { LiarState, LiarView } from '@bg/games/liar';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import type { Conn, Room } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function practice(person = 'A') {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const logs: string[] = [];
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: '철수', avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0, log: (level, msg) => level !== 'info' && logs.push(msg) });
|
||||
const room = manager.createPractice(person, 'liar') as Room;
|
||||
rooms.push(room);
|
||||
const msgs: ServerMessage[] = [];
|
||||
const conn: Conn & { msgs: ServerMessage[] } = { userId: person, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
room.join(conn, 'player');
|
||||
const state = () => room.game!.state as LiarState;
|
||||
const lastView = () => (msgs.filter((m) => m.t === 'state').at(-1) as Extract<ServerMessage, { t: 'state' }>).view as LiarView;
|
||||
/** Lets the computers act (their own timers) and the room clock run, until `stop` or the end. */
|
||||
const run = (stop: () => boolean = () => false, maxSteps = 4000) => {
|
||||
for (let i = 0; i < maxSteps && !room.game!.finished && !stop(); i++) {
|
||||
const next = Math.min(room.bots.dueAt ?? Infinity, room.effectiveDeadline() ?? Infinity);
|
||||
expect(Number.isFinite(next)).toBe(true);
|
||||
clock.advance(Math.max(0, next - clock.now()));
|
||||
room.bots.fire();
|
||||
room.onTimer();
|
||||
}
|
||||
};
|
||||
return { room, clock, msgs, conn, state, lastView, run, logs };
|
||||
}
|
||||
|
||||
describe('라이어 게임 room flow with computers', () => {
|
||||
test('연습 방은 사람 1 + 컴퓨터 4, 컴퓨터 채팅은 항상 켜짐', () => {
|
||||
const { room } = practice();
|
||||
expect(room.seatedIds().filter(isBotId)).toHaveLength(4);
|
||||
expect(room.start('A')).toBeNull();
|
||||
expect(room.game!.players).toHaveLength(5);
|
||||
});
|
||||
|
||||
test('사람이 차례에 설명하고 토론·투표하면 컴퓨터와 한 판이 끝까지 가요', () => {
|
||||
const { room, state, lastView, msgs, run, logs } = practice();
|
||||
expect(room.start('A')).toBeNull();
|
||||
expect(room.chat('A', '안녕')).toBe('게임 중에는 게임 화면의 채팅을 써 주세요.');
|
||||
const s0 = state();
|
||||
const iAmLiar = s0.liar === 'A';
|
||||
// Nothing the person receives names the liar or (if they are the liar) the word, until the reveal.
|
||||
const leaks = () => {
|
||||
const all = JSON.stringify(msgs.filter((m) => m.t === 'state').map((m) => ({ ...(m as { view: LiarView }).view, final: null, events: [] })));
|
||||
if (iAmLiar) expect(all).not.toContain(`"${s0.word}"`);
|
||||
expect(all).not.toContain('"liar":true');
|
||||
};
|
||||
let cs = 1;
|
||||
let described = 0;
|
||||
// Reveal: the person confirms; the computers confirm on their own.
|
||||
room.act('A', cs++, { type: 'ready' });
|
||||
run(() => state().phase.kind !== 'reveal');
|
||||
expect(state().phase.kind).toBe('describe');
|
||||
const speaker = () => GAMES.liar!.view(state(), null).phase.speaker;
|
||||
while (state().phase.kind === 'describe') {
|
||||
if (speaker() === 'A') {
|
||||
room.act('A', cs++, { type: 'chat', text: iAmLiar ? '저는 좋아하는 편이에요' : '음 다들 아실 거예요' });
|
||||
described++;
|
||||
}
|
||||
run(() => state().phase.kind !== 'describe' || speaker() === 'A');
|
||||
}
|
||||
leaks();
|
||||
expect(described).toBe(state().options.rounds);
|
||||
// Every computer described in its turn.
|
||||
for (const d of state().descriptions) if (d.from !== 'A') expect(d.text).not.toBeNull();
|
||||
expect(state().phase.kind).toBe('discussion');
|
||||
room.act('A', cs++, { type: 'chat', text: '누가 라이어일까요' });
|
||||
room.act('A', cs++, { type: 'ready' });
|
||||
run(() => state().phase.kind !== 'discussion');
|
||||
// The computers talked in the discussion.
|
||||
expect(state().chat.some((m) => isBotId(m.from))).toBe(true);
|
||||
leaks();
|
||||
while (state().phase.kind === 'vote') {
|
||||
const v = lastView();
|
||||
if (v.my!.voteTargets.length && v.my!.vote === null) room.act('A', cs++, { type: 'vote', target: v.my!.voteTargets[0]! });
|
||||
run(() => state().phase.kind !== 'vote' || (state().phase.kind === 'vote' && (state().phase as { round: number }).round !== v.phase.voteRound));
|
||||
}
|
||||
if (state().phase.kind === 'guess' && state().liar === 'A') room.act('A', cs++, { type: 'guess', text: '모르겠어요' });
|
||||
run();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
const f = state().final!;
|
||||
expect(f.summary).toMatch(/^(라이어|시민) 승리!/);
|
||||
const end = lastView();
|
||||
expect(end.final!.liar).toBe(s0.liar);
|
||||
expect(end.players.find((p) => p.id === s0.liar)!.liar).toBe(true);
|
||||
expect(logs).toEqual([]);
|
||||
});
|
||||
|
||||
test('사람이 아무것도 안 해도(시간 초과만) 끝나요', () => {
|
||||
const { room, run, state, logs } = practice();
|
||||
room.start('A');
|
||||
run();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(state().descriptions.filter((d) => d.from === 'A').every((d) => d.text === null)).toBe(true);
|
||||
expect(logs).toEqual([]);
|
||||
});
|
||||
|
||||
test('모든 시간 무제한: 컴퓨터는 알아서 하고, 연결이 끊긴 사람은 유예 시간 뒤 넘겨져 끝까지 가요', () => {
|
||||
const { room, conn, run, state, logs } = practice();
|
||||
const none = { describeSeconds: null, discussionSeconds: null, voteSeconds: null, guessSeconds: null };
|
||||
expect(room.configure('A', { options: { ...(room.config.options as object), ...none } })).toBeNull();
|
||||
room.start('A');
|
||||
room.disconnect(conn);
|
||||
run();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(state().options.describeSeconds).toBeNull();
|
||||
expect(state().descriptions.filter((d) => d.from === 'A').every((d) => d.text === null)).toBe(true);
|
||||
expect(logs).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,7 @@ import { openDb } from '../db';
|
||||
import { Room, type Conn, type RoomConfig } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
function harness(players: string[]) {
|
||||
function harness(players: string[], options: Record<string, unknown> = {}) {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
@@ -16,7 +16,7 @@ function harness(players: string[]) {
|
||||
const deps = { store, games, users: { publicUser: (id: string) => ({ id, nickname: id, avatar: null, kind: 'guest' as const }) }, now: clock.now };
|
||||
const config: RoomConfig = {
|
||||
gameId: 'mafia',
|
||||
options: { ...games.mafia.defaultOptions, firstPhase: 'night' },
|
||||
options: { ...games.mafia.defaultOptions, firstPhase: 'night', ...options },
|
||||
maxPlayers: players.length,
|
||||
visibility: 'private',
|
||||
allowSpectators: true,
|
||||
@@ -67,4 +67,23 @@ describe('마피아 room flow', () => {
|
||||
expect(state().phase.kind).toBe('discussion');
|
||||
expect(state().day).toBe(2);
|
||||
});
|
||||
|
||||
test('밤 시간 무제한: 타이머 없이 모두 밤 마치기를 누를 때까지, 연결이 끊긴 사람은 유예 시간 뒤 넘김', () => {
|
||||
const { room, clock, conns, state } = harness(['A', 'B', 'C', 'D'], { nightSeconds: null });
|
||||
expect(room.start('A')).toBeNull();
|
||||
clock.advance(8_000);
|
||||
room.onTimer();
|
||||
expect(state().phase.kind).toBe('night');
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
let cs = 10;
|
||||
for (const p of ['A', 'B', 'C']) room.act(p, ++cs, { type: 'readyEarly' });
|
||||
clock.advance(3_600_000);
|
||||
room.onTimer();
|
||||
expect(state().phase.kind).toBe('night');
|
||||
room.disconnect(conns.D!);
|
||||
expect(room.effectiveDeadline()).toBe(clock.now() + 60_000);
|
||||
clock.advance(60_000);
|
||||
room.onTimer();
|
||||
expect(state().phase.kind).toBe('discussion');
|
||||
});
|
||||
});
|
||||
|
||||
103
apps/server/src/rooms/magical-athlete.room.test.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
/** 야단법석 달리기 through a real Room: practice games against computers played to the end from the person's own screen (docs/games/magical-athlete.md §10). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { MagicalAthleteAction, MagicalAthleteState, MagicalAthleteView } from '@bg/games/magical-athlete';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
return { db, clock, manager, conn };
|
||||
}
|
||||
|
||||
type StateMsg = Extract<ServerMessage, { t: 'state' }>;
|
||||
const views = (c: { msgs: ServerMessage[] }) => c.msgs.filter((m): m is StateMsg => m.t === 'state').map((m) => m.view as MagicalAthleteView);
|
||||
|
||||
/** What the person presses, read only from their own screen (uses a power whenever one is offered). */
|
||||
function personMove(v: MagicalAthleteView, me: string, n: number): MagicalAthleteAction | null {
|
||||
if (v.phase === 'draft') return v.draft!.picker === me ? { type: 'DRAFT', racer: v.draft!.line[n % v.draft!.line.length]! } : null;
|
||||
if (v.phase === 'select') {
|
||||
if (v.picked[me]) return null;
|
||||
const left = v.teams[me]!.filter((id) => !v.used[me]!.includes(id));
|
||||
return { type: 'SELECT', racers: left.slice(0, v.perRace) };
|
||||
}
|
||||
const pr = v.prompt;
|
||||
if (v.phase !== 'race' || !pr || pr.owner !== me) return null;
|
||||
if (pr.step === 'go') return { type: 'GO', racer: pr.options[0]!.key as never };
|
||||
if (pr.step === 'roll') return n % 4 === 3 && pr.options.some((o) => o.key === 'use') ? { type: 'CHOOSE', key: 'use' } : { type: 'ROLL' };
|
||||
return { type: 'CHOOSE', key: n % 2 === 0 ? pr.options[0]!.key : 'skip' };
|
||||
}
|
||||
|
||||
describe('야단법석 달리기 room flow', () => {
|
||||
test.each([1, 3])('컴퓨터 %i명과 연습: 사람은 자기 화면만 보고 끝까지, 컴퓨터가 고른 출전 선수는 경주 전까지 안 보여요', (nBots) => {
|
||||
const h = harness();
|
||||
let room: Room;
|
||||
if (nBots === 1) room = h.manager.createPractice('A', 'magical-athlete') as Room;
|
||||
else {
|
||||
const r = h.manager.create('A', 'magical-athlete', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
room = r;
|
||||
for (let i = 0; i < nBots; i++) expect(room.addBot('A')).toBeNull();
|
||||
}
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bots = room.game!.players.filter(isBotId);
|
||||
expect(bots).toHaveLength(nBots);
|
||||
let cs = 0;
|
||||
let seen = 0;
|
||||
let mine = 0;
|
||||
for (let i = 0; i < 40_000 && !room.game!.finished; i++) {
|
||||
h.clock.advance(250);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
const vs = views(a);
|
||||
// A computer's secret pick never reaches my screen before the race starts.
|
||||
for (const v of vs.slice(seen)) {
|
||||
if (v.phase === 'select') for (const b of bots) expect(JSON.stringify(v)).not.toContain(`-${b}-`);
|
||||
expect(v.me).toBe('A');
|
||||
}
|
||||
seen = vs.length;
|
||||
const v = vs.at(-1);
|
||||
const m = v && personMove(v, 'A', mine);
|
||||
if (m) {
|
||||
room.act('A', ++cs, m);
|
||||
mine++;
|
||||
}
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
|
||||
const s = room.game!.state as MagicalAthleteState;
|
||||
expect(s.results).toHaveLength(4);
|
||||
expect(s.timeouts.A).toBe(0); // every step of the person was a real press
|
||||
expect(s.perRace).toBe(nBots === 1 ? 2 : 1);
|
||||
for (const p of s.seats) expect(s.used[p]).toHaveLength(4 * s.perRace);
|
||||
const last = views(a).at(-1)!;
|
||||
expect(last.result!.ranking.map((r) => r.player).sort()).toEqual(['A', ...bots].sort());
|
||||
const total = (p: string) => last.scores[p]!.total;
|
||||
expect(last.result!.ranking[0]!.total).toBe(Math.max(...s.seats.map(total)));
|
||||
expect(mine).toBeGreaterThan(20);
|
||||
const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!;
|
||||
expect(JSON.parse(row.result_json).practice).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -115,6 +115,7 @@ export class RoomManager {
|
||||
allowSpectators: true,
|
||||
chatEnabled: site?.chatEnabledDefault ?? true,
|
||||
chatFilter: site?.chatFilterDefault ?? true,
|
||||
botChat: false,
|
||||
graceSec: site?.graceSec ?? 60,
|
||||
};
|
||||
const code = this.newCode();
|
||||
|
||||
@@ -226,3 +226,43 @@ describe('윷놀이 room rules', () => {
|
||||
expect(st.view.turnSeq).toBe((room.game!.state as any).turnSeq);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Room chat (2026-10-13)', () => {
|
||||
test('a quick burst of lines all goes through; a flood is still stopped', () => {
|
||||
const { room, clock, conn } = harness();
|
||||
const a = conn('A');
|
||||
const b = conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
for (let i = 0; i < 4; i++) expect(room.chat('A', `줄 ${i}`)).toBeNull();
|
||||
expect(room.chat('A', '도배')).toBe('조금 천천히 보내 주세요.');
|
||||
clock.advance(500);
|
||||
expect(room.chat('A', '0.5초 뒤')).toBeNull();
|
||||
expect(b.msgs.filter((m) => m.t === 'chat').map((m) => (m as { text: string }).text)).toEqual(['줄 0', '줄 1', '줄 2', '줄 3', '0.5초 뒤']);
|
||||
});
|
||||
|
||||
test('"입력 중" reaches the others (not me), repeats within a second are dropped, off always goes', () => {
|
||||
const { room, clock, conn } = harness();
|
||||
const a = conn('A');
|
||||
const b = conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
const typingOf = (c: { msgs: ServerMessage[] }) => c.msgs.filter((m) => m.t === 'typing');
|
||||
room.typing('A', true, 'room');
|
||||
room.typing('A', true, 'room');
|
||||
expect(typingOf(b)).toEqual([{ t: 'typing', from: 'A', on: true, ch: 'room' }]);
|
||||
expect(typingOf(a)).toHaveLength(0);
|
||||
clock.advance(1000);
|
||||
room.typing('A', true, 'room');
|
||||
room.typing('A', false, 'room');
|
||||
expect(typingOf(b)).toHaveLength(3);
|
||||
// Game chat signal only while a game with its own chat runs (omok has none).
|
||||
room.typing('A', true, 'game');
|
||||
expect(typingOf(b)).toHaveLength(3);
|
||||
// Chat off: nothing.
|
||||
room.configure('A', { chatEnabled: false });
|
||||
clock.advance(1000);
|
||||
room.typing('A', true, 'room');
|
||||
expect(typingOf(b)).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
import { ulid } from 'ulid';
|
||||
import { SeededRng, createSeed, secureRandom, seedToHex, type AnyGameDefinition, type ChaChaSeed, type GameResult, type RngState } from '@bg/engine';
|
||||
import { botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type BotPick, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared';
|
||||
import { botChatRequired, botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type BotPick, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared';
|
||||
import { botPersona } from '@bg/games/bots';
|
||||
import { luckApplies, shufflesFor, type LuckJob } from '@bg/games/bots/luck';
|
||||
import { sha256Hex } from '../auth/sessions';
|
||||
@@ -14,6 +14,7 @@ import { BotBrain, type BotActivity } from '../ai/brain';
|
||||
import type { Llm } from '../ai/llm';
|
||||
import type { LogEntry, RoomStore } from './store';
|
||||
import { applyLocks, type EffectiveGame, type SiteSettings } from '../admin/settings';
|
||||
import { TokenBucket } from '../ws/rate-limit';
|
||||
|
||||
export interface Conn {
|
||||
userId: string;
|
||||
@@ -29,6 +30,8 @@ export interface RoomConfig {
|
||||
allowSpectators: boolean;
|
||||
chatEnabled: boolean;
|
||||
chatFilter: boolean;
|
||||
/** Computers chat on their own (docs/06 §12.1). Off unless the host turns it on; rooms saved before it existed read as off. */
|
||||
botChat?: boolean;
|
||||
/** Seconds a disconnected player keeps their turn timer before auto actions kick in (docs/03 §6.2). */
|
||||
graceSec: number;
|
||||
}
|
||||
@@ -149,6 +152,9 @@ export class Room {
|
||||
private flushTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private recentCs = new Map<string, number[]>();
|
||||
private lastChatAt = new Map<string, number>();
|
||||
private chatBuckets = new Map<string, TokenBucket>();
|
||||
/** When each person last said they were typing (to drop repeats within a second). */
|
||||
private typingAt = new Map<string, number>();
|
||||
private consecutiveErrors = 0;
|
||||
private readonly now: () => number;
|
||||
/** Plays the computer players' moves (docs/06 §12). */
|
||||
@@ -189,7 +195,9 @@ export class Room {
|
||||
},
|
||||
recentChat: () => this.chatLog.slice(-8).map((m) => ({ from: m.from?.nickname ?? '누군가', text: m.text })),
|
||||
smart: (bot) => botPersona(bot, this.profile(bot).base).smart,
|
||||
chatty: () => this.botChatOn(),
|
||||
now: this.now,
|
||||
view: (viewer) => (this.game && !this.game.finished ? this.def.view(this.game.state, viewer) : null),
|
||||
},
|
||||
deps.ai ?? null,
|
||||
deps.aiRandom ?? secureRandom,
|
||||
@@ -222,6 +230,11 @@ export class Room {
|
||||
);
|
||||
}
|
||||
|
||||
/** The computers' own chat: the room setting, or always where the game needs it (마피아). */
|
||||
private botChatOn(): boolean {
|
||||
return botChatRequired(this.config.gameId) || this.config.botChat === true;
|
||||
}
|
||||
|
||||
get def(): AnyGameDefinition {
|
||||
const d = this.deps.games[this.config.gameId];
|
||||
if (!d) throw new Error(`unknown game ${this.config.gameId}`);
|
||||
@@ -411,6 +424,7 @@ export class Room {
|
||||
allowSpectators: this.config.allowSpectators,
|
||||
chatEnabled: this.config.chatEnabled,
|
||||
chatFilter: this.config.chatFilter,
|
||||
botChat: this.botChatOn(),
|
||||
seats,
|
||||
spectators: [...this.spectators].map(pub),
|
||||
status: this.status,
|
||||
@@ -689,7 +703,7 @@ export class Room {
|
||||
else if (next.gameId === this.config.gameId && this.config.maxPlayers === this.playerRange().max) next.maxPlayers = range.max;
|
||||
next.maxPlayers = Math.min(Math.max(next.maxPlayers, range.min), range.max);
|
||||
if (next.maxPlayers < this.seatedIds().length) return `이미 ${this.seatedIds().length}명이 앉아 있어요.`;
|
||||
for (const k of ['visibility', 'allowSpectators', 'chatEnabled', 'chatFilter'] as const) {
|
||||
for (const k of ['visibility', 'allowSpectators', 'chatEnabled', 'chatFilter', 'botChat'] as const) {
|
||||
if (patch[k] !== undefined) (next as unknown as Record<string, unknown>)[k] = patch[k];
|
||||
}
|
||||
// Resize seats, compacting occupied seats to the front if needed.
|
||||
@@ -789,8 +803,11 @@ export class Room {
|
||||
if (!this.isParticipant(userId)) return '방에 들어와야 채팅할 수 있어요.';
|
||||
if (this.gameChatOnly()) return '게임 중에는 게임 화면의 채팅을 써 주세요.';
|
||||
const now = this.now();
|
||||
if (now - (this.lastChatAt.get(userId) ?? 0) < 500) return '조금 천천히 보내 주세요.';
|
||||
this.lastChatAt.set(userId, now);
|
||||
// A few lines in a row go through (people often send 2~3 quick lines); a flood still stops.
|
||||
let bucket = this.chatBuckets.get(userId);
|
||||
if (!bucket) this.chatBuckets.set(userId, (bucket = new TokenBucket(2, 4, now)));
|
||||
if (!bucket.take(now)) return '조금 천천히 보내 주세요.';
|
||||
this.typingAt.delete(userId);
|
||||
const clean = text.replace(/[\u0000-\u001f\u007f]/g, ' ').trim();
|
||||
if (!clean) return null;
|
||||
const msg: Extract<ServerMessage, { t: 'chat' }> = {
|
||||
@@ -811,6 +828,21 @@ export class Room {
|
||||
return (this.status === 'playing' || this.status === 'paused') && !!this.def.ownChat;
|
||||
}
|
||||
|
||||
/**
|
||||
* "입력 중" for people, like the computers'. Room chat: only while the room chat is open. Game chat: only in games
|
||||
* with their own chat, and the client only sends it from the public channel (마피아 낮, 라이어 토론).
|
||||
*/
|
||||
typing(userId: string, on: boolean, ch: 'room' | 'game'): void {
|
||||
if (!this.isParticipant(userId)) return;
|
||||
if (ch === 'room' ? !this.config.chatEnabled || this.gameChatOnly() : !this.gameChatOnly()) return;
|
||||
const now = this.now();
|
||||
if (on) {
|
||||
if (now - (this.typingAt.get(userId) ?? -Infinity) < 1000) return;
|
||||
this.typingAt.set(userId, now);
|
||||
} else this.typingAt.delete(userId);
|
||||
for (const [id, c] of this.conns) if (id !== userId) c.send({ t: 'typing', from: userId, on, ch });
|
||||
}
|
||||
|
||||
emote(userId: string, id: string): void {
|
||||
if (!this.isParticipant(userId) || this.gameChatOnly()) return;
|
||||
const now = this.now();
|
||||
|
||||
90
apps/server/src/rooms/uno.room.test.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
/** 우노 with computers in a real room (docs/games/uno.md §9.1): a person and three computers play to the end. */
|
||||
import { afterEach, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import type { UnoState } from '@bg/games/uno';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import type { Conn, Room } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function practice(options: Record<string, unknown> = {}) {
|
||||
const store = new RoomStore(openDb(':memory:'));
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const room = manager.createPractice('A', 'uno') as Room;
|
||||
rooms.push(room);
|
||||
const msgs: ServerMessage[] = [];
|
||||
const a: Conn = { userId: 'A', send: (m) => msgs.push(m), close: () => {} };
|
||||
room.join(a, 'player');
|
||||
room.addBot('A');
|
||||
room.addBot('A');
|
||||
room.configure('A', { options: { ...(room.config.options as object), ...options } });
|
||||
expect(room.start('A')).toBeNull();
|
||||
return { room, clock, msgs, a };
|
||||
}
|
||||
|
||||
/** Bots move at once; when the game waits on the person, they play their first legal action (or the clock runs out). */
|
||||
function playToEnd(room: Room, clock: { advance: (ms: number) => void }, humanActs: boolean): number {
|
||||
const def = GAMES.uno!;
|
||||
let cs = 0;
|
||||
let steps = 0;
|
||||
for (; steps < 20_000 && !room.game!.finished; steps++) {
|
||||
if (room.bots.dueAt !== null) {
|
||||
room.bots.fire();
|
||||
continue;
|
||||
}
|
||||
const s = room.game!.state as UnoState;
|
||||
const legal = def.legalActions!(s, 'A');
|
||||
if (humanActs && legal.length && def.activePlayers(s).includes('A')) {
|
||||
room.act('A', ++cs, legal.find((x) => (x as { type: string }).type !== 'catchUno') ?? legal[0]);
|
||||
continue;
|
||||
}
|
||||
clock.advance(61_000);
|
||||
room.onTimer();
|
||||
}
|
||||
return steps;
|
||||
}
|
||||
|
||||
test('a person and three computers finish a game of 우노 (person plays)', () => {
|
||||
const { room, clock } = practice();
|
||||
expect(room.game!.players.filter(isBotId)).toHaveLength(3);
|
||||
playToEnd(room, clock, true);
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(room.status).toBe('finished');
|
||||
});
|
||||
|
||||
test('500 points with house rules: the person only times out, the computers still finish', () => {
|
||||
const { room, clock, msgs } = practice({ scoring: 'to500', stacking: true, drawUntilPlayable: true });
|
||||
playToEnd(room, clock, false);
|
||||
expect(room.game!.finished).toBe(true);
|
||||
const s = room.game!.state as UnoState;
|
||||
expect(s.rounds.length).toBeGreaterThanOrEqual(1);
|
||||
expect(msgs.some((m) => m.t === 'state')).toBe(true);
|
||||
// The person's screen shows card counts only for the computers.
|
||||
const view = JSON.stringify(GAMES.uno!.view(s, 'A'));
|
||||
for (const bot of s.seats.filter(isBotId)) for (const c of s.hands[bot]!) expect(view).not.toContain(`"${c.id}"`);
|
||||
});
|
||||
|
||||
test('무제한 time: no clock while the person is here; a dropped connection is still auto-played after the grace time', () => {
|
||||
const { room, clock, a } = practice({ turnSeconds: null });
|
||||
// Let the computers move until the game waits on the person.
|
||||
for (let i = 0; i < 200 && room.bots.dueAt !== null; i++) room.bots.fire();
|
||||
const s = () => room.game!.state as UnoState;
|
||||
expect(GAMES.uno!.activePlayers(s())).toContain('A');
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
const turn = s().turnNo;
|
||||
room.disconnect(a);
|
||||
const d = room.effectiveDeadline();
|
||||
expect(d).not.toBeNull();
|
||||
clock.advance(d! - clock.advance(0) + 1);
|
||||
room.onTimer();
|
||||
expect(s().turnNo !== turn || s().log.some((e) => e.t === 'timeout' && e.p === 'A')).toBe(true);
|
||||
});
|
||||
@@ -208,6 +208,9 @@ export class Gateway {
|
||||
case 'emote':
|
||||
room.emote(u, m.id);
|
||||
return;
|
||||
case 'typing':
|
||||
room.typing(u, m.on, m.ch);
|
||||
return;
|
||||
case 'rematch':
|
||||
e = room.rematch(u);
|
||||
break;
|
||||
|
||||
@@ -1,18 +1,30 @@
|
||||
import type { RoomView } from '@bg/shared/lite';
|
||||
import { useRoom } from '../net/socket';
|
||||
|
||||
/**
|
||||
* What the computers are doing right now (docs/06 §12.1): "🤖 컴퓨터 1 생각 중…", "💬 컴퓨터 2 입력 중…".
|
||||
* What the computers are doing right now (docs/06 §12.1): "🤖 컴퓨터 1 생각 중…", "💬 컴퓨터 2 입력 중…", and people
|
||||
* typing ("💬 고양이 입력 중…", `ch`: the room chat or the game's own public chat).
|
||||
* Not announced to screen readers: the chat line or the move that follows is.
|
||||
*/
|
||||
export function BotActivity({ room, only }: { room: RoomView; only?: 'typing' }) {
|
||||
export function BotActivity({ room, only, ch }: { room: RoomView; only?: 'typing'; ch?: 'room' | 'game' }) {
|
||||
const typing = useRoom((s) => s.typing);
|
||||
const me = useRoom((s) => s.me?.id);
|
||||
const entries = Object.entries(room.botActivity ?? {}).filter(([, a]) => !only || a === only);
|
||||
if (!entries.length) return null;
|
||||
const name = (id: string) => room.seats.find((s) => s?.user.id === id)?.user.nickname ?? '컴퓨터';
|
||||
const people = ch ? Object.entries(typing).filter(([id, t]) => t.ch === ch && id !== me) : [];
|
||||
if (!entries.length && !people.length) return null;
|
||||
const name = (id: string, fallback: string) =>
|
||||
room.seats.find((s) => s?.user.id === id)?.user.nickname ?? room.spectators.find((u) => u.id === id)?.nickname ?? fallback;
|
||||
return (
|
||||
<div className="bot-activity small" aria-hidden>
|
||||
{entries.map(([id, a]) => (
|
||||
<span key={id} data-activity={a}>
|
||||
{a === 'typing' ? '💬' : '🤖'} {name(id)} {a === 'typing' ? '입력 중' : '생각 중'}
|
||||
{a === 'typing' ? '💬' : '🤖'} {name(id, '컴퓨터')} {a === 'typing' ? '입력 중' : '생각 중'}
|
||||
<span className="bot-dots" />
|
||||
</span>
|
||||
))}
|
||||
{people.map(([id]) => (
|
||||
<span key={id} data-activity="typing" data-person>
|
||||
💬 {name(id, '누군가')} 입력 중
|
||||
<span className="bot-dots" />
|
||||
</span>
|
||||
))}
|
||||
|
||||
29
apps/web/src/components/ChatMessage.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* One chat message, shared by the room chat and the games with their own chat (마피아, 라이어 게임): the name sits on
|
||||
* its own small coloured line above a bubble with the text, so who said it and what they said never run together.
|
||||
* My own messages sit on the right without a name; a run of messages from the same person shows the name once.
|
||||
* Hidden names stay in the DOM for screen readers (`.sr-only`).
|
||||
*/
|
||||
import type { CSSProperties, ReactNode } from 'react';
|
||||
|
||||
/** Hues that stay readable as text on the panel in both themes (lightness comes from `--chat-name-l`). */
|
||||
const HUES = [212, 152, 28, 275, 335, 188, 48, 0, 248, 100];
|
||||
|
||||
export function nameHue(id: string): number {
|
||||
let h = 0;
|
||||
for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) >>> 0;
|
||||
return HUES[h % HUES.length]!;
|
||||
}
|
||||
|
||||
export function ChatMessage({ from, name, mine = false, cont = false, className, children }: { from: string; name: string; mine?: boolean; cont?: boolean; className?: string; children: ReactNode }) {
|
||||
return (
|
||||
<div className={`chat-line${mine ? ' mine' : ''}${cont ? ' cont' : ''}${className ? ` ${className}` : ''}`} style={{ '--name-h': nameHue(from) } as CSSProperties}>
|
||||
<strong className={`chat-name${mine || cont ? ' sr-only' : ''}`}>{mine ? '나' : name}</strong>
|
||||
<span className="chat-text">{children}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Same sender as the message right before, within 2 minutes: the name is not repeated. */
|
||||
type RunKey = { from?: string | null; at: number } | undefined;
|
||||
export const sameRun = (prev: RunKey, cur: RunKey): boolean => !!prev && !!cur?.from && prev.from === cur.from && cur.at - prev.at < 120_000;
|
||||
@@ -3,20 +3,25 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { CHAT_MAX, EMOTE_LABEL, EMOTES, type PublicUser, type RoomView } from '@bg/shared/lite';
|
||||
import { create } from 'zustand';
|
||||
import { socket, useRoom } from '../net/socket';
|
||||
import { useChatOutbox, useTypingSignal } from '../lib/chat-input';
|
||||
import { useStickToBottom } from '../lib/useStickToBottom';
|
||||
import { BotActivity } from './BotActivity';
|
||||
import { ChatMessage, sameRun } from './ChatMessage';
|
||||
|
||||
/** Id of the newest chat line shown in an open chat panel (ids only grow; the list itself keeps the last 100). */
|
||||
export const useChatSeen = create<{ seen: number }>(() => ({ seen: 0 }));
|
||||
|
||||
export function ChatPanel({ room, me, title = true }: { room: RoomView; me: PublicUser; title?: boolean }) {
|
||||
const chat = useRoom((s) => s.chat);
|
||||
const [text, setText] = useState('');
|
||||
const [hidden, setHidden] = useState<Set<string>>(new Set());
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const { ref: listRef, pin } = useStickToBottom<HTMLDivElement>();
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const send = useChatOutbox((t) => socket.send({ t: 'chat', text: t }), 550);
|
||||
const typing = useTypingSignal('room', room.chatEnabled);
|
||||
const lastId = chat.at(-1)?.id ?? 0;
|
||||
useEffect(() => {
|
||||
useChatSeen.setState({ seen: chat.length });
|
||||
listRef.current?.scrollTo({ top: listRef.current.scrollHeight });
|
||||
}, [chat.length]);
|
||||
useChatSeen.setState({ seen: lastId });
|
||||
}, [lastId]);
|
||||
// Enter anywhere (outside inputs) focuses chat — PC shortcut (docs/07 §3.5).
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
@@ -34,26 +39,20 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
|
||||
{title && <h2 style={{ fontSize: '1.1rem' }}>채팅</h2>}
|
||||
<div ref={listRef} className="chat-list" aria-live="polite">
|
||||
{chat.length === 0 && <p className="muted small">아직 메시지가 없어요. Enter를 누르면 바로 입력할 수 있어요.</p>}
|
||||
{chat
|
||||
.filter((m) => !m.from || !hidden.has(m.from.id))
|
||||
.map((m) => (
|
||||
<div key={m.id} className="chat-line">
|
||||
<strong>{m.from?.nickname ?? '알림'}</strong>
|
||||
{chat.map((m, i) =>
|
||||
m.from ? (
|
||||
<ChatMessage key={m.id} from={m.from.id} name={m.from.nickname} mine={m.from.id === me.id} cont={sameRun(chatKey(chat[i - 1]), chatKey(m))}>
|
||||
{m.text}
|
||||
</ChatMessage>
|
||||
) : (
|
||||
<div key={m.id} className="chat-line sys">
|
||||
<strong className="sr-only">알림</strong>
|
||||
{m.text}
|
||||
{m.from && m.from.id !== me.id && (
|
||||
<button
|
||||
className="muted small"
|
||||
style={{ border: 0, background: 'none', cursor: 'pointer' }}
|
||||
title="이 사람의 채팅 가리기"
|
||||
onClick={() => setHidden(new Set([...hidden, m.from!.id]))}
|
||||
>
|
||||
가리기
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
<BotActivity room={room} only="typing" />
|
||||
<BotActivity room={room} only="typing" ch="room" />
|
||||
<div className="emote-row">
|
||||
{EMOTES.map((id) => (
|
||||
<button key={id} type="button" onClick={() => socket.send({ t: 'emote', id })}>
|
||||
@@ -67,8 +66,10 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
|
||||
style={{ flexWrap: 'nowrap' }}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (text.trim()) socket.send({ t: 'chat', text: text.trim().slice(0, CHAT_MAX) });
|
||||
if (text.trim()) send(text.trim().slice(0, CHAT_MAX));
|
||||
setText('');
|
||||
typing.stop();
|
||||
pin();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
@@ -76,7 +77,11 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
|
||||
className="input"
|
||||
style={{ flex: 1, minHeight: 44 }}
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onChange={(e) => {
|
||||
setText(e.target.value);
|
||||
typing.onText(e.target.value);
|
||||
}}
|
||||
onBlur={typing.stop}
|
||||
onKeyDown={(e) => e.key === 'Escape' && (e.currentTarget as HTMLInputElement).blur()}
|
||||
maxLength={CHAT_MAX}
|
||||
placeholder="메시지 입력 (Enter)"
|
||||
@@ -92,6 +97,8 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
|
||||
);
|
||||
}
|
||||
|
||||
const chatKey = (m: { from?: { id: string } | null; at: number } | undefined) => m && { from: m.from?.id ?? null, at: m.at };
|
||||
|
||||
/** Floating emote bubbles (both layouts). */
|
||||
export function EmoteBubbles({ room }: { room: RoomView }) {
|
||||
const emotes = useRoom((s) => s.emotes);
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
/** PC top menu (docs/07-ui-ux.md §3.2): 로고·메뉴, 오른쪽에 테마 버튼과 로그인/계정 메뉴. */
|
||||
/** PC top menu (docs/07-ui-ux.md §3.2): 로고·메뉴, 오른쪽에 소리 크기·테마 버튼과 로그인/계정 메뉴. */
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, NavLink, useNavigate } from 'react-router';
|
||||
import { api } from '../net/api';
|
||||
import { useSession } from '../store/session';
|
||||
import { Avatar, ConfirmSheet } from './ui';
|
||||
import { VolumeControl } from './VolumeControl';
|
||||
|
||||
export function SiteHeader() {
|
||||
const { me, siteName, role } = useSession();
|
||||
@@ -21,7 +22,10 @@ export function SiteHeader() {
|
||||
<NavLink to="/games">게임 목록</NavLink>
|
||||
{role !== 'user' && <NavLink to="/admin">관리자</NavLink>}
|
||||
</nav>
|
||||
<ThemeToggle />
|
||||
<div className="header-tools">
|
||||
<VolumeControl />
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
{me ? (
|
||||
<AccountMenu />
|
||||
) : (
|
||||
|
||||
84
apps/web/src/components/VolumeControl.tsx
Normal file
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* Site volume (top right of the site header and the room bar): a speaker button that opens a 0~100 slider.
|
||||
* Default 50 (the sounds play at half their old level). 0 or "소리 끄기" mutes everything. This device only.
|
||||
*/
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { sfx } from '../lib/feedback';
|
||||
import { useSession } from '../store/session';
|
||||
|
||||
export function volumeIcon(sound: boolean, volume: number): string {
|
||||
if (!sound || volume <= 0) return '🔇';
|
||||
return volume < 34 ? '🔈' : volume < 67 ? '🔉' : '🔊';
|
||||
}
|
||||
|
||||
export function VolumeControl({ className = 'theme-toggle', label }: { className?: string; label?: boolean }) {
|
||||
const sound = useSession((s) => s.settings.sound);
|
||||
const volume = useSession((s) => s.settings.volume);
|
||||
const updateSettings = useSession((s) => s.updateSettings);
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onDown = (e: PointerEvent) => !ref.current?.contains(e.target as Node) && setOpen(false);
|
||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setOpen(false);
|
||||
document.addEventListener('pointerdown', onDown);
|
||||
document.addEventListener('keydown', onKey);
|
||||
return () => {
|
||||
document.removeEventListener('pointerdown', onDown);
|
||||
document.removeEventListener('keydown', onKey);
|
||||
};
|
||||
}, [open]);
|
||||
const shown = sound ? volume : 0;
|
||||
const icon = volumeIcon(sound, volume);
|
||||
return (
|
||||
<div className="volume-control" ref={ref}>
|
||||
<button
|
||||
type="button"
|
||||
className={className}
|
||||
aria-label={`소리 크기 ${shown}`}
|
||||
title={`소리 크기 ${shown}`}
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
>
|
||||
{label ? (
|
||||
<>
|
||||
<span className="rb-ico">{icon}</span>
|
||||
<span className="rb-lbl">{shown}</span>
|
||||
</>
|
||||
) : (
|
||||
<span aria-hidden>{icon}</span>
|
||||
)}
|
||||
</button>
|
||||
{open && (
|
||||
<div className="volume-pop" role="dialog" aria-label="소리 크기">
|
||||
<div className="row" style={{ justifyContent: 'space-between', flexWrap: 'nowrap', gap: 8 }}>
|
||||
<strong>소리 크기</strong>
|
||||
<output className="volume-num" aria-live="polite">
|
||||
{shown}
|
||||
</output>
|
||||
</div>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={100}
|
||||
step={5}
|
||||
value={shown}
|
||||
aria-label="소리 크기 (0~100)"
|
||||
onChange={(e) => updateSettings({ volume: Number(e.target.value), sound: Number(e.target.value) > 0 })}
|
||||
onPointerUp={() => sfx.good()}
|
||||
onKeyUp={() => sfx.click()}
|
||||
/>
|
||||
<div className="row" style={{ justifyContent: 'space-between', flexWrap: 'nowrap', gap: 8 }}>
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={() => updateSettings(sound && volume > 0 ? { sound: false } : { sound: true, volume: volume > 0 ? volume : 50 })}>
|
||||
{sound && volume > 0 ? '🔇 끄기' : '🔊 켜기'}
|
||||
</button>
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={() => (updateSettings({ sound: true, volume: 50 }), sfx.good())}>
|
||||
기본(50)
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
/**
|
||||
* Hwatu card drawn in SVG (our own simple artwork, no commercial hwatu images — docs/games/seotda.md §12).
|
||||
* Large month number + kind badge so the card is readable without knowing the pictures.
|
||||
* Hwatu card: the real 48-card hwatu artwork from Wikimedia Commons "SVG Hwatu" (Marcus Richert after Louie Mantia Jr.,
|
||||
* CC BY-SA 4.0 — ./hwatu/ATTRIBUTION.txt, docs/games/seotda.md "화투 그림"), bundled from our own origin (no external
|
||||
* URLs). A small month badge stays on top so beginners can read the card at a glance;
|
||||
* 쌍피 / bonus cards get their value tag (고스톱). The back and the bonus cards are drawn here.
|
||||
*/
|
||||
import type { CSSProperties, ReactNode } from 'react';
|
||||
import type { CSSProperties } from 'react';
|
||||
|
||||
export interface HwatuInfo {
|
||||
id: number;
|
||||
@@ -13,172 +15,180 @@ export interface HwatuInfo {
|
||||
piValue?: number;
|
||||
}
|
||||
|
||||
const MONTH_COLOR = ['#6b7280', '#15803d', '#be185d', '#db2777', '#1f2937', '#7c3aed', '#dc2626', '#b91c1c', '#111827', '#ca8a04', '#c2410c', '#7c2d12', '#1e40af'];
|
||||
const MONTH_NAME = ['보너스', '송학', '매조', '벚꽃', '흑싸리', '난초', '모란', '홍싸리', '공산', '국화', '단풍', '오동', '비'];
|
||||
const KIND_BADGE: Record<HwatuInfo['kind'], string> = { gwang: '光', yeol: '열', tti: '띠', pi: '피', ssangpi: '쌍피', bonus: '+' };
|
||||
const TTI_COLOR = { hong: '#dc2626', cheong: '#2563eb', cho: '#15803d', plain: '#dc2626' };
|
||||
const TTI_TEXT = { hong: '홍단', cheong: '청단', cho: '', plain: '' };
|
||||
/** Attribution of the card artwork (CC BY-SA 4.0 asks for it); shown in the rules of the games that use these cards. */
|
||||
export const HWATU_CREDIT =
|
||||
'화투 그림: Marcus Richert(Louie Mantia, Jr.의 Hanafuda 그림 바탕), Spenĉjo — Wikimedia Commons "SVG Hwatu", CC BY-SA 4.0 (https://creativecommons.org/licenses/by-sa/4.0/). 크기만 줄여 썼어요.';
|
||||
|
||||
/** A small motif per month (flowers/plants), drawn with basic shapes. */
|
||||
function Motif({ month, color }: { month: number; color: string }): ReactNode {
|
||||
const c = color;
|
||||
switch (month) {
|
||||
case 1: // 송학: pine
|
||||
return <path d="M50 52 L28 92 H72 Z M50 72 L22 116 H78 Z" fill={c} opacity="0.85" />;
|
||||
case 2: // 매조: plum blossoms
|
||||
case 3: // 벚꽃
|
||||
return (
|
||||
<g fill={c} opacity="0.85">
|
||||
{[[34, 70], [62, 62], [50, 92], [70, 100], [30, 108]].map(([x, y], i) => (
|
||||
<circle key={i} cx={x} cy={y} r="10" />
|
||||
))}
|
||||
</g>
|
||||
);
|
||||
case 4: // 흑싸리
|
||||
case 7: // 홍싸리
|
||||
return (
|
||||
<g stroke={c} strokeWidth="5" strokeLinecap="round" opacity="0.85">
|
||||
{[30, 45, 60, 75].map((x, i) => (
|
||||
<line key={i} x1={x} y1="52" x2={x - 6} y2={100 + (i % 2) * 14} />
|
||||
))}
|
||||
</g>
|
||||
);
|
||||
case 5: // 난초: iris leaves
|
||||
return (
|
||||
<g fill="none" stroke={c} strokeWidth="5" opacity="0.85">
|
||||
<path d="M40 120 Q34 80 44 52" />
|
||||
<path d="M55 120 Q62 84 52 54" />
|
||||
<path d="M70 120 Q76 92 68 64" />
|
||||
</g>
|
||||
);
|
||||
case 6: // 모란: peony
|
||||
return (
|
||||
<g fill={c} opacity="0.85">
|
||||
<circle cx="50" cy="86" r="22" />
|
||||
<circle cx="50" cy="86" r="10" fill="#fde68a" />
|
||||
</g>
|
||||
);
|
||||
case 8: // 공산: hill
|
||||
return <path d="M8 120 Q50 52 92 120 Z" fill={c} opacity="0.85" />;
|
||||
case 9: // 국화
|
||||
return (
|
||||
<g fill={c} opacity="0.9">
|
||||
{Array.from({ length: 10 }, (_, i) => {
|
||||
const a = (i / 10) * Math.PI * 2;
|
||||
return <ellipse key={i} cx={50 + Math.cos(a) * 14} cy={88 + Math.sin(a) * 14} rx="8" ry="4" transform={`rotate(${(a * 180) / Math.PI} ${50 + Math.cos(a) * 14} ${88 + Math.sin(a) * 14})`} />;
|
||||
})}
|
||||
<circle cx="50" cy="88" r="7" fill="#78350f" />
|
||||
</g>
|
||||
);
|
||||
case 10: // 단풍: maple
|
||||
return <path d="M50 58 L58 78 L78 74 L64 90 L74 108 L50 98 L26 108 L36 90 L22 74 L42 78 Z" fill={c} opacity="0.9" />;
|
||||
case 11: // 오동
|
||||
return (
|
||||
<g fill={c} opacity="0.85">
|
||||
<ellipse cx="38" cy="82" rx="16" ry="22" />
|
||||
<ellipse cx="64" cy="94" rx="16" ry="22" />
|
||||
</g>
|
||||
);
|
||||
case 12: // 비: rain lines + umbrella
|
||||
return (
|
||||
<g stroke={c} strokeWidth="3" opacity="0.85">
|
||||
{[20, 35, 50, 65, 80].map((x) => (
|
||||
<line key={x} x1={x} y1="54" x2={x - 8} y2="118" />
|
||||
))}
|
||||
</g>
|
||||
);
|
||||
default:
|
||||
return <text x="50" y="98" fontSize="36" textAnchor="middle" fill={c}>★</text>;
|
||||
}
|
||||
export type HwatuSize = 'sm' | 'md' | 'lg' | 'xl';
|
||||
const WIDTH: Record<HwatuSize, number> = { sm: 40, md: 60, lg: 84, xl: 108 };
|
||||
/** Height / width of the artwork (103.2 × 168.2). */
|
||||
export const HWATU_RATIO = 1.63;
|
||||
|
||||
/**
|
||||
* URL of a card face (ids 0..47). Vite turns this pattern into hashed /assets/ files (cached for good, also by the
|
||||
* service worker); in tests it is just a file URL.
|
||||
*/
|
||||
export const hwatuSrc = (id: number): string => new URL(`./hwatu/${id}.svg`, import.meta.url).href;
|
||||
|
||||
/** Card back: deep red lacquer with a thin gold frame, like a real hwatu back. */
|
||||
export function HwatuBack({ w, h }: { w: number; h: number }) {
|
||||
return (
|
||||
<svg viewBox="0 0 100 163" width={w} height={h} aria-hidden style={{ display: 'block' }}>
|
||||
<defs>
|
||||
<linearGradient id="hwb-g" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stopColor="#c8102e" />
|
||||
<stop offset="1" stopColor="#8a0b1f" />
|
||||
</linearGradient>
|
||||
<pattern id="hwb-p" width="10" height="10" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
|
||||
<rect width="10" height="10" fill="none" />
|
||||
<path d="M0 5h10M5 0v10" stroke="#ffffff" strokeOpacity="0.07" strokeWidth="1.2" />
|
||||
</pattern>
|
||||
</defs>
|
||||
<rect x="1" y="1" width="98" height="161" rx="7" fill="url(#hwb-g)" stroke="#4a0510" strokeWidth="2" />
|
||||
<rect x="1" y="1" width="98" height="161" rx="7" fill="url(#hwb-p)" />
|
||||
<rect x="8" y="8" width="84" height="147" rx="4" fill="none" stroke="#f6c453" strokeOpacity="0.55" strokeWidth="1.5" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export type HwatuSize = 'sm' | 'md' | 'lg';
|
||||
const WIDTH: Record<HwatuSize, number> = { sm: 40, md: 60, lg: 84 };
|
||||
function BonusFace({ w, h, value }: { w: number; h: number; value: number }) {
|
||||
return (
|
||||
<svg viewBox="0 0 100 163" width={w} height={h} aria-hidden style={{ display: 'block' }}>
|
||||
<rect x="1" y="1" width="98" height="161" rx="7" fill="#e3262b" />
|
||||
<rect x="7" y="7" width="86" height="149" rx="5" fill="#fffaf0" />
|
||||
<circle cx="50" cy="70" r="27" fill="#f6c453" stroke="#b45309" strokeWidth="3" />
|
||||
<text x="50" y="81" fontSize="30" fontWeight="900" fill="#7c2d12" textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
{value}
|
||||
</text>
|
||||
<text x="50" y="128" fontSize="20" fontWeight="900" fill="#b91c1c" textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
보너스
|
||||
</text>
|
||||
<text x="50" y="148" fontSize="15" fontWeight="800" fill="#7c2d12" textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
{value}피
|
||||
</text>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function HwatuCard({
|
||||
card,
|
||||
size = 'md',
|
||||
width,
|
||||
selected,
|
||||
dimmed,
|
||||
highlight,
|
||||
showMonth = true,
|
||||
onClick,
|
||||
className,
|
||||
style,
|
||||
}: {
|
||||
card: HwatuInfo | null;
|
||||
size?: HwatuSize;
|
||||
/** Exact width in px (overrides `size`). */
|
||||
width?: number;
|
||||
selected?: boolean;
|
||||
dimmed?: boolean;
|
||||
highlight?: boolean;
|
||||
/** Small month number badge (on by default). */
|
||||
showMonth?: boolean;
|
||||
onClick?: () => void;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
}) {
|
||||
const w = WIDTH[size];
|
||||
const h = Math.round(w * 1.6);
|
||||
const w = width ?? WIDTH[size];
|
||||
const h = Math.round(w * HWATU_RATIO);
|
||||
const Tag = onClick ? 'button' : 'span';
|
||||
const radius = Math.max(3, Math.round(w * 0.07));
|
||||
const s: CSSProperties = {
|
||||
position: 'relative',
|
||||
width: w,
|
||||
height: h,
|
||||
flex: 'none',
|
||||
display: 'inline-block',
|
||||
padding: 0,
|
||||
border: 0,
|
||||
borderRadius: radius,
|
||||
background: 'none',
|
||||
cursor: onClick ? 'pointer' : 'default',
|
||||
opacity: dimmed ? 0.45 : 1,
|
||||
transform: selected ? `translateY(${-Math.round(w * 0.2)}px)` : undefined,
|
||||
transition: 'transform 0.12s ease',
|
||||
filter: highlight ? 'drop-shadow(0 0 6px #f59e0b)' : 'drop-shadow(0 1px 2px rgba(0,0,0,0.3))',
|
||||
boxShadow: selected ? '0 0 0 3px #2563eb' : undefined,
|
||||
filter: highlight ? 'drop-shadow(0 0 6px #f59e0b)' : 'drop-shadow(0 1px 2px rgba(0,0,0,0.35))',
|
||||
verticalAlign: 'bottom',
|
||||
...style,
|
||||
};
|
||||
if (!card) {
|
||||
return (
|
||||
<Tag style={s} onClick={onClick} aria-label="뒤집힌 화투">
|
||||
<svg viewBox="0 0 100 160" width={w} height={h} aria-hidden>
|
||||
<rect x="1" y="1" width="98" height="158" rx="8" fill="#991b1b" stroke="#450a0a" strokeWidth="3" />
|
||||
<rect x="10" y="10" width="80" height="140" rx="5" fill="#b91c1c" />
|
||||
</svg>
|
||||
<Tag style={s} onClick={onClick} aria-label="뒤집힌 화투" className={className}>
|
||||
<HwatuBack w={w} h={h} />
|
||||
</Tag>
|
||||
);
|
||||
}
|
||||
const color = MONTH_COLOR[card.month] ?? '#374151';
|
||||
const badge = Math.max(12, Math.round(w * 0.24));
|
||||
// 고스톱 passes 쌍피 as kind 'pi' with piValue 2.
|
||||
const tag = card.kind === 'ssangpi' || (card.kind === 'pi' && (card.piValue ?? 1) >= 2) ? '쌍피' : null;
|
||||
return (
|
||||
<Tag style={s} onClick={onClick} aria-label={card.name} aria-pressed={onClick ? !!selected : undefined} title={card.name}>
|
||||
<svg viewBox="0 0 100 160" width={w} height={h} aria-hidden>
|
||||
<rect x="1" y="1" width="98" height="158" rx="8" fill="#fffaf0" stroke={selected ? '#2563eb' : '#1f2937'} strokeWidth={selected ? 6 : 3} />
|
||||
{card.kind === 'bonus' ? (
|
||||
<text x="50" y="102" fontSize="34" fontWeight="900" fill="#b45309" textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
{card.piValue ?? 2}피
|
||||
</text>
|
||||
) : (
|
||||
<Motif month={card.month} color={color} />
|
||||
)}
|
||||
{card.kind === 'tti' && (
|
||||
<g>
|
||||
<rect x="58" y="30" width="18" height="90" rx="3" fill={TTI_COLOR[card.tti ?? 'plain']} />
|
||||
{TTI_TEXT[card.tti ?? 'plain'] && (
|
||||
<text x="67" y="62" fontSize="13" fontWeight="800" fill="#fff" textAnchor="middle" style={{ writingMode: 'vertical-rl' } as CSSProperties}>
|
||||
{TTI_TEXT[card.tti ?? 'plain']}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
)}
|
||||
{(card.kind === 'gwang' || card.kind === 'yeol') && (
|
||||
<g>
|
||||
<circle cx="78" cy="120" r="15" fill={card.kind === 'gwang' ? '#dc2626' : '#a16207'} />
|
||||
<text x="78" y="127" fontSize={card.kind === 'gwang' ? 20 : 16} fontWeight="800" fill="#fff" textAnchor="middle">
|
||||
{card.kind === 'gwang' ? '光' : '열'}
|
||||
</text>
|
||||
</g>
|
||||
)}
|
||||
{/* Month number: large and always readable */}
|
||||
<rect x="6" y="6" width="38" height="38" rx="8" fill={color} />
|
||||
<text x="25" y="35" fontSize="28" fontWeight="900" fill="#fff" textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
{card.month || '+'}
|
||||
</text>
|
||||
<text x="50" y="154" fontSize="13" fontWeight="700" fill="#374151" textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
{MONTH_NAME[card.month]} · {card.kind === 'bonus' ? `${card.piValue ?? 2}피` : card.kind === 'tti' ? (TTI_TEXT[card.tti ?? 'plain'] || '띠') : KIND_BADGE[card.kind] === '光' ? '광' : KIND_BADGE[card.kind] === '열' ? '열끗' : KIND_BADGE[card.kind]}
|
||||
</text>
|
||||
</svg>
|
||||
<Tag
|
||||
style={s}
|
||||
onClick={onClick}
|
||||
aria-label={card.name}
|
||||
aria-pressed={onClick ? !!selected : undefined}
|
||||
title={card.name}
|
||||
className={className}
|
||||
>
|
||||
{card.kind === 'bonus' || card.id >= 48 ? (
|
||||
<BonusFace w={w} h={h} value={card.piValue ?? 2} />
|
||||
) : (
|
||||
<img src={hwatuSrc(card.id)} alt="" draggable={false} width={w} height={h} decoding="async" style={{ display: 'block', width: w, height: h, borderRadius: radius }} />
|
||||
)}
|
||||
{showMonth && card.month > 0 && (
|
||||
<span
|
||||
aria-hidden
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: Math.round(w * 0.05),
|
||||
right: Math.round(w * 0.05),
|
||||
minWidth: badge,
|
||||
height: badge,
|
||||
padding: '0 2px',
|
||||
borderRadius: badge,
|
||||
background: 'rgba(17,24,39,0.82)',
|
||||
color: '#fff',
|
||||
fontSize: Math.max(9, Math.round(badge * 0.66)),
|
||||
fontWeight: 800,
|
||||
lineHeight: `${badge}px`,
|
||||
textAlign: 'center',
|
||||
fontFamily: 'Pretendard Variable, sans-serif',
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
>
|
||||
{card.month}
|
||||
</span>
|
||||
)}
|
||||
{tag && (
|
||||
<span
|
||||
aria-hidden
|
||||
style={{
|
||||
position: 'absolute',
|
||||
left: '50%',
|
||||
bottom: Math.round(w * 0.06),
|
||||
transform: 'translateX(-50%)',
|
||||
padding: '0 4px',
|
||||
borderRadius: 4,
|
||||
background: '#f6c453',
|
||||
color: '#7c2d12',
|
||||
fontSize: Math.max(9, Math.round(w * 0.2)),
|
||||
fontWeight: 900,
|
||||
lineHeight: 1.25,
|
||||
whiteSpace: 'nowrap',
|
||||
fontFamily: 'Pretendard Variable, sans-serif',
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
>
|
||||
{tag}
|
||||
</span>
|
||||
)}
|
||||
</Tag>
|
||||
);
|
||||
}
|
||||
|
||||
1
apps/web/src/components/cards/hwatu/0.svg
Normal file
|
After Width: | Height: | Size: 26 KiB |
1
apps/web/src/components/cards/hwatu/1.svg
Normal file
|
After Width: | Height: | Size: 19 KiB |
1
apps/web/src/components/cards/hwatu/10.svg
Normal file
|
After Width: | Height: | Size: 51 KiB |
1
apps/web/src/components/cards/hwatu/11.svg
Normal file
|
After Width: | Height: | Size: 56 KiB |
1
apps/web/src/components/cards/hwatu/12.svg
Normal file
|
After Width: | Height: | Size: 34 KiB |
1
apps/web/src/components/cards/hwatu/13.svg
Normal file
|
After Width: | Height: | Size: 28 KiB |
1
apps/web/src/components/cards/hwatu/14.svg
Normal file
|
After Width: | Height: | Size: 26 KiB |
1
apps/web/src/components/cards/hwatu/15.svg
Normal file
|
After Width: | Height: | Size: 27 KiB |
1
apps/web/src/components/cards/hwatu/16.svg
Normal file
|
After Width: | Height: | Size: 29 KiB |
1
apps/web/src/components/cards/hwatu/17.svg
Normal file
|
After Width: | Height: | Size: 21 KiB |
1
apps/web/src/components/cards/hwatu/18.svg
Normal file
|
After Width: | Height: | Size: 18 KiB |
1
apps/web/src/components/cards/hwatu/19.svg
Normal file
|
After Width: | Height: | Size: 20 KiB |
1
apps/web/src/components/cards/hwatu/2.svg
Normal file
|
After Width: | Height: | Size: 12 KiB |
1
apps/web/src/components/cards/hwatu/20.svg
Normal file
|
After Width: | Height: | Size: 50 KiB |
1
apps/web/src/components/cards/hwatu/21.svg
Normal file
|
After Width: | Height: | Size: 27 KiB |
1
apps/web/src/components/cards/hwatu/22.svg
Normal file
|
After Width: | Height: | Size: 29 KiB |
1
apps/web/src/components/cards/hwatu/23.svg
Normal file
|
After Width: | Height: | Size: 23 KiB |
1
apps/web/src/components/cards/hwatu/24.svg
Normal file
|
After Width: | Height: | Size: 54 KiB |
1
apps/web/src/components/cards/hwatu/25.svg
Normal file
|
After Width: | Height: | Size: 27 KiB |
1
apps/web/src/components/cards/hwatu/26.svg
Normal file
|
After Width: | Height: | Size: 24 KiB |
1
apps/web/src/components/cards/hwatu/27.svg
Normal file
|
After Width: | Height: | Size: 20 KiB |
1
apps/web/src/components/cards/hwatu/28.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg width="103.2" height="168.2" preserveAspectRatio="none" version="1.1" viewBox="0 0 103.2 168.2" xmlns="http://www.w3.org/2000/svg"><path d="m13.3 7.2c-4.67 0-7 2.33-7 7v139.8c0 4.67 2.33 7 7 7h76.6c4.67 0 7-2.33 7-7v-139.8c0-4.67-2.33-7-7-7z" fill="#fff"/><path d="m3.3 3.15c-.17 10.85 1.3 101.25 1.3 101.25l94.7 9.5 1.25-110.75c-32.28.58-64.87-1.85-97.25 0zm46.45 19c18.68-.54 33.23 16.56 33.23 31.59 0 21.84-16.42 34.31-33.38 34.31-14.18 0-32.68-12.1-32.68-32.42 0-16.47 11.61-32.87 32.83-33.48z" fill="#ef1d1e"/><path d="m48.05 21.45c-8.53.4-15.92 3.75-22.15 10.05-6.6 6.67-9.78 14.78-9.55 24.35.37 11.97 5.65 21.23 15.85 27.8 6.37 4.07 13.38 5.7 21.05 4.9 9.1-.97 16.6-4.95 22.5-11.95 5.73-6.77 8.32-14.82 7.75-24.15-.5-8.27-3.9-15.47-10.2-21.6-6.9-6.7-15.32-9.83-25.25-9.4zm.92 1.21c6.93-.28 13.46 1.72 19.58 5.99 6.2 4.33 10.35 10.15 12.45 17.45 2.8 9.93 1.22 19.15-4.75 27.65-2.9 4.13-6.42 7.37-10.55 9.7-3.97 2.23-8.35 3.55-13.15 3.95-8.4.3-15.68-1.82-21.85-6.35-5.63-4.17-9.48-9.43-11.55-15.8-2.87-9.07-2.08-17.63 2.35-25.7h.05l.05-.05c4.57-8.23 11.33-13.5 20.3-15.8 2.4-.6 4.76-.95 7.07-1.04zm-8.22 70.09c-2.53.27-4.43.43-5.7.5-.6 0-1.35.08-2.25.25-.97.17-1.7.28-2.2.35-.17.03-1.22.23-3.15.6-2.37.57-3.83.93-4.4 1.1l-6.5 2.25c-.8.27-1.9.72-3.3 1.35-1.5.67-2.62 1.13-3.35 1.4-2.03.73-3.97 1.77-5.8 3.1l-.82 59.4 95.11 1.07-.89-52.96c-1-.87-2.92-2.22-5.75-4.05-2.03-1.33-4.47-2.8-7.3-4.4-1.93-1.1-4.67-2.38-8.2-3.85-3.03-1.1-5.3-1.93-6.8-2.5-2.13-.77-5.77-1.65-10.9-2.65-.43-.07-2.75-.28-6.95-.65l-2.75-.2c-.47 0-1.13-.03-2-.1l-3.1.05c-1.33-.07-2.33-.08-3-.05z"/><g transform="translate(479.2 -235.55)"><path transform="translate(-848.6,2.2)" d="m399.45 353.05c-4.87 0-9.02 1.72-12.45 5.15-3.4 3.43-5.1 7.58-5.1 12.45s1.7 9.02 5.1 12.45c3.43 3.43 7.58 5.15 12.45 5.15s9.02-1.72 12.45-5.15 5.15-7.58 5.15-12.45-1.72-9.02-5.15-12.45-7.58-5.15-12.45-5.15z" fill="#ef1d1e"/><path transform="translate(-848.6,2.2)" d="m397.62 356.15c-.52.06-.91.55-1.17 1.45-.3 1-.3 2.55 0 4.65.03.93.05 1.82.05 2.65-.03.97-.1 1.85-.2 2.65-.73.23-1.38.47-1.95.7-2.07.83-3.1 1.65-3.1 2.45v.25l.15.4h.4c.03 0 1.67-.4 4.9-1.2-.27.9-.85 1.93-1.75 3.1-.83 1.1-1.58 1.97-2.25 2.6-.7.67-1.15 1.12-1.35 1.35-.13.2-.52.55-1.15 1.05-.6.47-1.18.82-1.75 1.05-.6.23-.9.48-.9.75 0 .17.13.35.4.55.27.17.6.25 1 .25.97 0 2.25-.8 3.85-2.4 1.6-1.63 2.65-2.78 3.15-3.45s1.1-1.62 1.8-2.85c.67-1.23 1.15-2.1 1.45-2.6v-.05c.06 0 .11-.02.15-.05-.04.04-.09.07-.15.1.07 1.03.13 2 .2 2.9l-.35 5.5c0 1.33.38 2.27 1.15 2.8.73.5 2.27.78 4.6.85 2.3.13 4.07-.32 5.3-1.35 1.33-1.07 1.93-2.18 1.8-3.35-.07-1.13-.35-1.95-.85-2.45s-.92-.82-1.25-.95c-.4-.07-.78.48-1.15 1.65-.43 1.13-.92 1.82-1.45 2.05-.57.2-1.37.4-2.4.6-1.07.3-1.73.45-2 .45-1 0-1.52-1.07-1.55-3.2.07-2.1.1-3.2.1-3.3 0-.97-.02-1.55-.05-1.75-.13-.3-.37-.6-.7-.9 2.83-1 4.25-1.88 4.25-2.65 0-.53-.2-.87-.6-1-.17-.1-.58-.15-1.25-.15-.6 0-1.22.15-1.85.45-1.1.47-1.9.8-2.4 1-.07-.33-.1-.77-.1-1.3 0-.83.08-1.77.25-2.8 0-.2.02-.42.05-.65.17-1.3.25-2.32.25-3.05s-.02-1.23-.05-1.5c-.23-.87-.67-1.3-1.3-1.3-.08-.01-.16-.01-.23 0zm5.73 1.75c-.6.47-1.38 1.22-2.35 2.25-.97 1.03-1.45 1.9-1.45 2.6 0 .67.02 1.02.05 1.05.07.07.1.12.1.15.13.1.23.15.3.15.33 0 1.27-.55 2.8-1.65 1.63-1.2 2.45-2.05 2.45-2.55 0-.43-.2-.87-.6-1.3-.4-.47-.83-.7-1.3-.7zm-12.5 4.6c-.3 0-.55.18-.75.55-.13.33-.2.65-.2.95 0 .83.17 1.45.5 1.85.3.3.77.48 1.4.55.2.03.43.05.7.05.2-.03.43-.08.7-.15.1-.03.22-.1.35-.2.83-.33 1.25-.75 1.25-1.25 0-.43-.15-.72-.45-.85-.17-.07-.62-.17-1.35-.3-.6-.07-1.02-.3-1.25-.7-.27-.33-.57-.5-.9-.5z" fill="#fff"/><path transform="translate(-848.6,2.2)" d="m399.45 353.05c-4.87 0-9.02 1.72-12.45 5.15-3.4 3.43-5.1 7.58-5.1 12.45s1.7 9.02 5.1 12.45c3.43 3.43 7.58 5.15 12.45 5.15s9.02-1.72 12.45-5.15 5.15-7.58 5.15-12.45-1.72-9.02-5.15-12.45-7.58-5.15-12.45-5.15z" fill="none" stroke="#000"/></g><g transform="translate(-447.2 -373.75)"><path transform="translate(160.15,84.1)" d="m292.05 289.65c-3.33 0-5 1.67-5 5v158.2c0 3.33 1.67 5 5 5h93.2c3.33 0 5-1.67 5-5v-158.2c0-3.33-1.67-5-5-5zm8.3 7.2h76.6c4.67 0 7 2.33 7 7v139.8c0 4.67-2.33 7-7 7h-76.6c-4.67 0-7-2.33-7-7v-139.8c0-4.67 2.33-7 7-7z" fill="#ef1d1e"/><path transform="translate(160.15,84.1)" d="m300.35 296.85c-4.67 0-7 2.33-7 7v139.8c0 4.67 2.33 7 7 7h76.6c4.67 0 7-2.33 7-7v-139.8c0-4.67-2.33-7-7-7z" fill="none" stroke="#000" stroke-width="1.2"/></g></svg>
|
||||
|
After Width: | Height: | Size: 4.2 KiB |
1
apps/web/src/components/cards/hwatu/29.svg
Normal file
|
After Width: | Height: | Size: 28 KiB |
1
apps/web/src/components/cards/hwatu/3.svg
Normal file
|
After Width: | Height: | Size: 10 KiB |
1
apps/web/src/components/cards/hwatu/30.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg width="103.2" height="168.2" preserveAspectRatio="none" version="1.1" viewBox="0 0 103.2 168.2" xmlns="http://www.w3.org/2000/svg"><path d="m13.3 7.2c-4.67 0-7 2.33-7 7v139.8c0 4.67 2.33 7 7 7h76.6c4.67 0 7-2.33 7-7v-139.8c0-4.67-2.33-7-7-7z" fill="#fff"/><path d="m41.15 88.75c-1.6.07-3.2.22-4.8.45-3.07.4-5.35.75-6.85 1.05-3.43.7-5.65 1.18-6.65 1.45-1.5.4-3.72 1.13-6.65 2.2-3.9 1.43-6.35 2.42-7.35 2.95-1.63.7-2.83 1.27-3.6 1.7l-1.7 67.5c.46.42 97.25 0 97.25 0l-3.7-59.55c-1.87-1.67-3.3-2.87-4.3-3.6-1.07-.77-2.7-1.82-4.9-3.15-2.3-1.3-4.32-2.38-6.05-3.25-1.27-.6-3.47-1.5-6.6-2.7-1.9-.73-3.6-1.3-5.1-1.7-2.2-.47-3.85-.83-4.95-1.1-2.73-.6-4.8-.98-6.2-1.15l-3.75-.55c-2.5-.23-4-.37-4.5-.4-2.17.1-3.78.07-4.85-.1-.87-.1-2.45-.12-4.75-.05z"/><g transform="translate(-555.75,-373.75)"><path transform="translate(160.15,84.1)" d="m400.6 289.65c-3.33 0-5 1.67-5 5v158.2c0 3.33 1.67 5 5 5h93.2c3.33 0 5-1.67 5-5v-158.2c0-3.33-1.67-5-5-5zm8.3 7.2h76.6c4.67 0 7 2.33 7 7v139.8c0 4.67-2.33 7-7 7h-76.6c-4.67 0-7-2.33-7-7v-139.8c0-4.67 2.33-7 7-7z" fill="#ef1d1e"/><path transform="translate(160.15,84.1)" d="m408.9 296.85c-4.67 0-7 2.33-7 7v139.8c0 4.67 2.33 7 7 7h76.6c4.67 0 7-2.33 7-7v-139.8c0-4.67-2.33-7-7-7z" fill="none" stroke="#000" stroke-width="1.2"/></g></svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
1
apps/web/src/components/cards/hwatu/31.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg width="103.2" height="168.2" preserveAspectRatio="none" version="1.1" viewBox="0 0 103.2 168.2" xmlns="http://www.w3.org/2000/svg"><path d="m13.3 7.2c-4.67 0-7 2.33-7 7v139.8c0 4.67 2.33 7 7 7h76.6c4.67 0 7-2.33 7-7v-139.8c0-4.67-2.33-7-7-7z" fill="#fff"/><path d="m46.2 81.65c-1.8 0-3.35.07-4.65.2-3.77.33-6.58.62-8.45.85-2.53.27-4.38.53-5.55.8-2.33.5-4.7 1.1-7.1 1.8-2.57.7-4.72 1.4-6.45 2.1-.37.17-2.32 1.1-5.85 2.8-1.93 1.07-3.32 1.97-4.15 2.7l-.6 73.15h97.25l-1.55-67.2c-1.27-1.1-2.14-1.82-2.6-2.15-.1-.07-.2-.11-.3-.18-.36-.28-.5-.48-.9-.77-.53-.4-2.22-1.48-5.05-3.25-1.93-1.2-4.27-2.4-7-3.6-1.33-.6-3.58-1.47-6.75-2.6-1.97-.77-3.3-1.23-4-1.4-2.77-.6-4.85-1.08-6.25-1.45-.4-.13-1.02-.22-1.85-.25-.87-.03-1.48-.1-1.85-.2-.8-.23-1.77-.42-2.9-.55-1.27-.13-2.23-.25-2.9-.35-2.13-.27-4.12-.4-5.95-.4-2.07-.03-3.6-.05-4.6-.05z"/><g transform="translate(-773.5,-373.75)"><path transform="translate(160.15,84.1)" d="m618.35 289.65c-3.33 0-5 1.67-5 5v158.2c0 3.33 1.67 5 5 5h93.2c3.33 0 5-1.67 5-5v-158.2c0-3.33-1.67-5-5-5zm8.3 7.2h76.6c4.67 0 7 2.33 7 7v139.8c0 4.67-2.33 7-7 7h-76.6c-4.67 0-7-2.33-7-7v-139.8c0-4.67 2.33-7 7-7z" fill="#ef1d1e"/><path transform="translate(160.15,84.1)" d="m626.65 296.85c-4.67 0-7 2.33-7 7v139.8c0 4.67 2.33 7 7 7h76.6c4.67 0 7-2.33 7-7v-139.8c0-4.67-2.33-7-7-7z" fill="none" stroke="#000" stroke-width="1.2"/></g></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
1
apps/web/src/components/cards/hwatu/32.svg
Normal file
|
After Width: | Height: | Size: 50 KiB |
1
apps/web/src/components/cards/hwatu/33.svg
Normal file
|
After Width: | Height: | Size: 37 KiB |
1
apps/web/src/components/cards/hwatu/34.svg
Normal file
|
After Width: | Height: | Size: 35 KiB |
1
apps/web/src/components/cards/hwatu/35.svg
Normal file
|
After Width: | Height: | Size: 36 KiB |
1
apps/web/src/components/cards/hwatu/36.svg
Normal file
|
After Width: | Height: | Size: 56 KiB |
1
apps/web/src/components/cards/hwatu/37.svg
Normal file
|
After Width: | Height: | Size: 32 KiB |
1
apps/web/src/components/cards/hwatu/38.svg
Normal file
|
After Width: | Height: | Size: 28 KiB |
1
apps/web/src/components/cards/hwatu/39.svg
Normal file
|
After Width: | Height: | Size: 30 KiB |
1
apps/web/src/components/cards/hwatu/4.svg
Normal file
|
After Width: | Height: | Size: 36 KiB |
1
apps/web/src/components/cards/hwatu/40.svg
Normal file
|
After Width: | Height: | Size: 36 KiB |
1
apps/web/src/components/cards/hwatu/41.svg
Normal file
|
After Width: | Height: | Size: 15 KiB |
1
apps/web/src/components/cards/hwatu/42.svg
Normal file
|
After Width: | Height: | Size: 18 KiB |
1
apps/web/src/components/cards/hwatu/43.svg
Normal file
|
After Width: | Height: | Size: 19 KiB |
1
apps/web/src/components/cards/hwatu/44.svg
Normal file
|
After Width: | Height: | Size: 54 KiB |
1
apps/web/src/components/cards/hwatu/45.svg
Normal file
|
After Width: | Height: | Size: 40 KiB |
1
apps/web/src/components/cards/hwatu/46.svg
Normal file
|
After Width: | Height: | Size: 18 KiB |
1
apps/web/src/components/cards/hwatu/47.svg
Normal file
|
After Width: | Height: | Size: 21 KiB |
1
apps/web/src/components/cards/hwatu/5.svg
Normal file
|
After Width: | Height: | Size: 30 KiB |
1
apps/web/src/components/cards/hwatu/6.svg
Normal file
|
After Width: | Height: | Size: 32 KiB |
1
apps/web/src/components/cards/hwatu/7.svg
Normal file
|
After Width: | Height: | Size: 25 KiB |
1
apps/web/src/components/cards/hwatu/8.svg
Normal file
|
After Width: | Height: | Size: 65 KiB |
1
apps/web/src/components/cards/hwatu/9.svg
Normal file
|
After Width: | Height: | Size: 55 KiB |
14
apps/web/src/components/cards/hwatu/ATTRIBUTION.txt
Normal file
@@ -0,0 +1,14 @@
|
||||
화투 그림 출처 (Hwatu card artwork)
|
||||
|
||||
0.svg ~ 47.svg (화투 48장, 파일 이름 = 게임 엔진의 카드 id = (월-1)*4 + 칸)
|
||||
|
||||
- 원본: Wikimedia Commons "Category:SVG Hwatu"
|
||||
https://commons.wikimedia.org/wiki/Category:SVG_Hwatu
|
||||
(File:Hwatu January Hikari.svg ~ File:Hwatu December Kasu.svg, 2026-10-13 받음)
|
||||
- 만든 사람: Marcus Richert (Louie Mantia, Jr.의 Hanafuda 그림을 바탕으로 한국 화투처럼 다시 칠하고 일부 선을 고침),
|
||||
카드별 파일 분리: Spenĉjo
|
||||
- 라이선스: CC BY-SA 4.0 (https://creativecommons.org/licenses/by-sa/4.0/)
|
||||
- 바꾼 점: 좌표를 소수 둘째 자리로 반올림하고 공백·주석을 지워 파일 크기를 줄였다. 그림 내용은 바꾸지 않았다.
|
||||
이 파일들(변형본)도 CC BY-SA 4.0 으로 배포한다.
|
||||
|
||||
원본 파일 → 이 폴더 파일 대응은 docs/games/seotda.md "화투 그림" 절에 있다.
|
||||
53
apps/web/src/games/apple/help.test.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { expect, test } from 'bun:test';
|
||||
import { setupGame, usersOf } from '../help-kit.test-util';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { helpNow } from './help';
|
||||
|
||||
const users = usersOf(['A', 'B', 'C']);
|
||||
const view = (s: unknown, who: string | null) => GAMES.apple!.view(s, who) as any;
|
||||
|
||||
function playing(options: Record<string, unknown> = {}) {
|
||||
const { state } = setupGame('apple', 3, options);
|
||||
state.phase = 'playing';
|
||||
return state;
|
||||
}
|
||||
|
||||
test('사과 게임: 카운트다운 / 진행 중 / 관전', () => {
|
||||
const { state: s0 } = setupGame('apple', 3, { timeLimitSec: 60 });
|
||||
const c = helpNow(view(s0, 'A'), 'A', users);
|
||||
expect(c).toContain('곧 시작해요');
|
||||
expect(c).toContain('1분');
|
||||
const s = playing();
|
||||
const t = helpNow(view(s, 'A'), 'A', users);
|
||||
expect(t).toContain('딱 10');
|
||||
expect(t).toContain('빈 칸은 합에 들어가지 않아서');
|
||||
expect(t).toContain('아직 아무도');
|
||||
expect(t).toContain('스페이스');
|
||||
s.score.B = 12;
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('지금 1등은 고양이님(사과 12개)');
|
||||
expect(helpNow(view(s, 'B'), 'B', users)).toContain('지금 1등은 나(사과 12개)');
|
||||
expect(helpNow(view(s, null), null, users)).toContain('가장 많이 지운 사람이 이겨요');
|
||||
});
|
||||
|
||||
test('사과 게임: 막힘 / 나감 / 끝', () => {
|
||||
const s = playing();
|
||||
s.status.A = 'stuck';
|
||||
s.score.A = 40;
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('사과 40개를 지웠어요');
|
||||
s.status.B = 'left';
|
||||
expect(helpNow(view(s, 'B'), 'B', users)).toContain('게임에서 나갔어요');
|
||||
s.phase = 'ended';
|
||||
s.final = { endReason: 'time', ranking: [], summary: '시간이 다 됐어요. 사과를 가장 많이 지운 사람이 이겼어요' };
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('시간이 다 됐어요');
|
||||
});
|
||||
|
||||
test('사과 게임: 제한 시간 무제한 / 여기까지', () => {
|
||||
const { state: s0 } = setupGame('apple', 3, { timeLimitSec: null });
|
||||
expect(helpNow(view(s0, 'A'), 'A', users)).toContain('제한 시간은 없어요');
|
||||
const s = playing({ timeLimitSec: null });
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('[여기까지 할래요]');
|
||||
expect(helpNow(view(s, null), null, users)).toContain('모두 끝냈을 때');
|
||||
s.status.A = 'done';
|
||||
s.score.A = 30;
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('여기까지 했어요. 사과 30개');
|
||||
});
|
||||
36
apps/web/src/games/apple/help.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
/** 사과 게임 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { AppleView } from '@bg/games/apple';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
|
||||
const HOW = '사과 여러 개를 직사각형으로 드래그해서 숫자 합이 딱 10이 되면 손을 떼요. 그 사과들이 사라지고 사라진 개수만큼 점수를 얻어요.';
|
||||
const KEYS = '키보드: 화살표로 칸을 옮기고 스페이스(또는 Enter)로 시작점, 한 번 더 눌러 끝점을 정해요. Esc는 취소예요.';
|
||||
|
||||
function leaders(v: AppleView, players: Record<string, PublicUser>, me: string | null): string {
|
||||
const live = v.seats.filter((s) => s.status !== 'left');
|
||||
if (live.length < 2) return '';
|
||||
const best = Math.max(...live.map((s) => s.score));
|
||||
if (best === 0) return '아직 아무도 사과를 지우지 않았어요.';
|
||||
const top = live.filter((s) => s.score === best).map((s) => (s.id === me ? '나' : `${players[s.id]?.nickname ?? '다른 사람'}님`));
|
||||
return `지금 1등은 ${top.join(', ')}(사과 ${best}개)예요.`;
|
||||
}
|
||||
|
||||
export function helpNow(v: AppleView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
if (v.phase === 'ended') return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n최종 순위에서 각자 지운 사과 개수를 볼 수 있어요.';
|
||||
const secs = v.options.timeLimitSec;
|
||||
const limitLine = secs === null ? '제한 시간은 없어요. 모두 끝낼 때까지 해요.' : `제한 시간은 ${secs % 60 === 0 ? `${secs / 60}분` : `${secs}초`}이에요.`;
|
||||
if (v.phase === 'countdown') return `곧 시작해요. 모두 똑같은 사과 판을 각자 풀어요. ${limitLine}\n${HOW}`;
|
||||
const mine = v.seats.find((s) => s.id === me) ?? null;
|
||||
const lead = leaders(v, players, me);
|
||||
const winLine = secs === null ? '모두 끝냈을 때' : '시간이 끝났을 때';
|
||||
if (!mine) return `모두 똑같은 판을 각자 풀고 있어요. ${winLine} 사과를 가장 많이 지운 사람이 이겨요.${lead ? `\n${lead}` : ''}`;
|
||||
if (mine.status === 'left') return '게임에서 나갔어요. 남은 사람들이 끝날 때까지 기다려 주세요.';
|
||||
if (mine.status === 'stuck') {
|
||||
return `내 판에는 이제 합이 10이 되는 사과 묶음이 없어요. 사과 ${mine.score}개를 지웠어요. ${secs === null ? '모두 끝내면' : '시간이 끝나거나 모두 막히면'} 순위가 나와요.${lead ? `\n${lead}` : ''}`;
|
||||
}
|
||||
if (mine.status === 'done') return `여기까지 했어요. 사과 ${mine.score}개를 지웠어요. 모두 끝내면 순위가 나와요.${lead ? `\n${lead}` : ''}`;
|
||||
const lines = [HOW, '빈 칸은 합에 들어가지 않아서, 사이가 비어 있어도 멀리 있는 사과끼리 묶을 수 있어요.', `지금 내 점수는 사과 ${mine.score}개예요.`];
|
||||
if (lead) lines.push(lead);
|
||||
if (secs === null) lines.push('제한 시간이 없어요. 그만하고 싶으면 아래 [여기까지 할래요]를 두 번 눌러요.');
|
||||
lines.push(KEYS);
|
||||
return lines.join('\n');
|
||||
}
|
||||
711
apps/web/src/games/apple/index.tsx
Normal file
@@ -0,0 +1,711 @@
|
||||
/** 사과 게임 화면 (docs/games/apple.md §9). */
|
||||
import { useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent, type ReactNode } from 'react';
|
||||
import type { AppleOptions, AppleView, SeatView } from '@bg/games/apple';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sfx, tone } from '../../lib/feedback';
|
||||
import { socket } from '../../net/socket';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
/** Canonical board: 10 rows × 17 columns (phones show it turned: 17 rows × 10 columns). */
|
||||
const ROWS = 10;
|
||||
const COLS = 17;
|
||||
/** SVG units per cell. */
|
||||
const S = 40;
|
||||
|
||||
type Cell = [number, number];
|
||||
interface Rect {
|
||||
r0: number;
|
||||
c0: number;
|
||||
r1: number;
|
||||
c1: number;
|
||||
}
|
||||
|
||||
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x));
|
||||
const rectOf = (a: Cell, b: Cell): Rect => ({ r0: Math.min(a[0], b[0]), c0: Math.min(a[1], b[1]), r1: Math.max(a[0], b[0]), c1: Math.max(a[1], b[1]) });
|
||||
|
||||
/** Apples (indices) inside a rectangle and their sum. */
|
||||
function inside(cells: string, r: Rect): { sum: number; idx: number[] } {
|
||||
let sum = 0;
|
||||
const idx: number[] = [];
|
||||
for (let y = r.r0; y <= r.r1; y++) {
|
||||
for (let x = r.c0; x <= r.c1; x++) {
|
||||
const v = cells.charCodeAt(y * COLS + x) - 48;
|
||||
if (v > 0) {
|
||||
sum += v;
|
||||
idx.push(y * COLS + x);
|
||||
}
|
||||
}
|
||||
}
|
||||
return { sum, idx };
|
||||
}
|
||||
|
||||
const clock = (ms: number) => {
|
||||
const s = Math.ceil(Math.max(0, ms) / 1000);
|
||||
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
|
||||
};
|
||||
const limitLabel = (sec: number | null) => (sec === null ? '무제한' : sec % 60 === 0 ? `${sec / 60}분` : `${sec}초`);
|
||||
|
||||
/** Game sounds on top of the shared palette (site volume applies). */
|
||||
const apSound = {
|
||||
/** Apples popping: one rising pop per apple (up to 5), quick enough to finish while they vanish. */
|
||||
clear: (n: number) => {
|
||||
for (let i = 0; i < Math.min(5, n); i++) tone(520 + i * 110, 80, 'sine', 0.16, i * 38, { slideTo: 1100 + i * 160 });
|
||||
},
|
||||
/** Let go on a sum that is not 10: a soft "thud", no penalty. */
|
||||
miss: () => tone(230, 90, 'triangle', 0.09, 0, { slideTo: 180 }),
|
||||
/** The box being dragged just added up to 10. */
|
||||
ten: () => tone(1320, 45, 'triangle', 0.07),
|
||||
count: () => tone(660, 90, 'triangle', 0.12),
|
||||
go: () => {
|
||||
tone(988, 120, 'triangle', 0.14);
|
||||
tone(1318, 200, 'triangle', 0.12, 90);
|
||||
},
|
||||
};
|
||||
|
||||
const statusSuffix = (s: SeatView) => (s.status === 'stuck' ? ', 더 지울 사과 없음' : s.status === 'done' ? ', 여기까지 함' : s.status === 'left' ? ', 나감' : '');
|
||||
|
||||
/** Ranks by score (ties share), players who left last. */
|
||||
function ranked(seats: SeatView[]): (SeatView & { rank: number })[] {
|
||||
const sorted = [...seats].sort((a, b) => Number(a.status === 'left') - Number(b.status === 'left') || b.score - a.score);
|
||||
const out: (SeatView & { rank: number })[] = [];
|
||||
sorted.forEach((s, i) => {
|
||||
const prev = out[i - 1];
|
||||
const tie = prev && prev.score === s.score && (prev.status === 'left') === (s.status === 'left');
|
||||
out.push({ ...s, rank: tie ? prev.rank : i + 1 });
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
const CSS = `
|
||||
.ap { width: 100%; display: flex; flex-direction: column; align-items: center; gap: 8px; }
|
||||
.ap-top { width: 100%; display: flex; flex-wrap: wrap; gap: 6px; align-items: center; justify-content: center; }
|
||||
.ap-pill { display: inline-flex; align-items: center; gap: 6px; border-radius: 999px; padding: 4px 12px; background: var(--surface); box-shadow: var(--shadow);
|
||||
font-weight: 800; font-variant-numeric: tabular-nums; font-size: 1rem; white-space: nowrap; }
|
||||
.ap-pill b { font-size: 1.2rem; }
|
||||
.ap-pill.warn { background: var(--danger-soft); color: var(--danger); }
|
||||
.ap-pill.sum { min-width: 104px; justify-content: center; border: 2px solid transparent; }
|
||||
.ap-pill.sum[data-s='ok'] { background: var(--success-soft); color: var(--success); border-color: var(--success); }
|
||||
.ap-pill.sum[data-s='over'] { background: var(--danger-soft); color: var(--danger); }
|
||||
.ap-pill.sum[data-s='idle'] { color: var(--text-sub); }
|
||||
.ap-others { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 4px 6px; justify-content: center; max-width: 100%; }
|
||||
.ap-others li { display: inline-flex; align-items: center; gap: 4px; border-radius: 999px; padding: 2px 8px 2px 3px; background: var(--surface-2); font-size: .85rem; font-weight: 700; max-width: 46vw; }
|
||||
.ap-others li span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.ap-others li b { font-variant-numeric: tabular-nums; }
|
||||
.ap-others li[data-me='true'] { background: var(--primary-soft); }
|
||||
.ap-others li[data-out='true'] { opacity: .55; }
|
||||
.ap-wrap { position: relative; width: min(100%, 980px, calc((100vh - var(--site-h) - 250px) * 1.7)); min-width: 280px; }
|
||||
.ap-wrap[data-phone='true'] { width: min(100%, 480px, max(280px, calc((100svh - 235px) / 1.7))); }
|
||||
.ap-board { display: block; width: 100%; height: auto; touch-action: none; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none;
|
||||
border-radius: 14px; background: #fff8e7; box-shadow: var(--shadow), inset 0 0 0 3px #e9c98a; cursor: crosshair; outline: none; }
|
||||
.ap-board:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); }
|
||||
.ap-board[data-off='true'] { cursor: default; }
|
||||
:root[data-theme='dark'] .ap-board { background: #3b2f22; box-shadow: var(--shadow), inset 0 0 0 3px #6b4f2a; }
|
||||
@media (prefers-color-scheme: dark) { :root[data-theme='auto'] .ap-board { background: #3b2f22; box-shadow: var(--shadow), inset 0 0 0 3px #6b4f2a; } }
|
||||
.ap-pop { animation: ap-pop .42s ease-out forwards; transform-box: fill-box; transform-origin: center; pointer-events: none; }
|
||||
.ap-burst { animation: ap-burst .45s ease-out forwards; transform-box: fill-box; transform-origin: center; pointer-events: none; }
|
||||
.ap-in { animation: ap-in .34s cubic-bezier(.3,1.5,.5,1) both; animation-delay: var(--d, 0ms); transform-box: fill-box; transform-origin: center; }
|
||||
.ap-pill b, .ap-others li b { display: inline-block; }
|
||||
.ap-over.count b { display: block; animation: ap-count .9s ease-out both; }
|
||||
.ap-stop { min-height: 40px; }
|
||||
.ap-over { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; pointer-events: none;
|
||||
border-radius: 14px; text-align: center; padding: 12px; }
|
||||
.ap-over.count { background: rgba(0,0,0,.35); color: #fff; font-size: 5rem; font-weight: 900; text-shadow: 0 3px 8px rgba(0,0,0,.5); }
|
||||
.ap-over.count small { font-size: 1.05rem; font-weight: 800; }
|
||||
.ap-over.note { inset: auto 8px 8px 8px; background: var(--surface); color: var(--text); box-shadow: var(--shadow); font-weight: 800; }
|
||||
.ap-flash { position: absolute; left: 50%; top: 8px; transform: translateX(-50%); z-index: 3; pointer-events: none; border-radius: 999px; padding: 4px 14px;
|
||||
font-weight: 900; font-size: 1.05rem; background: var(--surface); box-shadow: 0 4px 14px rgba(0,0,0,.25); animation: ap-flash .9s ease forwards; }
|
||||
.ap-flash.ok { color: var(--success); border: 3px solid var(--success); }
|
||||
.ap-flash.bad { color: var(--text-sub); border: 3px solid var(--border); }
|
||||
.ap-keys { color: var(--text-sub); font-size: .85rem; font-weight: 600; text-align: center; margin: 0; }
|
||||
@keyframes ap-burst { 0% { transform: scale(.5); opacity: .9; } 100% { transform: scale(1.6); opacity: 0; } }
|
||||
@keyframes ap-in { from { transform: scale(0); opacity: 0; } }
|
||||
@keyframes ap-count { 0% { transform: scale(1.8); opacity: 0; } 25% { transform: scale(1); opacity: 1; } 100% { transform: scale(.85); opacity: .85; } }
|
||||
@keyframes ap-pop { 0% { transform: scale(1); opacity: 1; } 40% { transform: scale(1.25); opacity: .9; } 100% { transform: scale(.2) translateY(-30px); opacity: 0; } }
|
||||
@keyframes ap-flash { 0% { opacity: 0; transform: translateX(-50%) scale(.8); } 15% { opacity: 1; transform: translateX(-50%) scale(1.05); } 70% { opacity: 1; } 100% { opacity: 0; } }
|
||||
@media (prefers-reduced-motion: reduce) { .ap-pop { animation-duration: .01s; } .ap-flash, .ap-in, .ap-burst, .ap-over.count b { animation: none; } .ap-burst { display: none; } }
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------- art
|
||||
|
||||
/** The apple shape in a 40×40 cell (number drawn on top). */
|
||||
function AppleDefs() {
|
||||
return (
|
||||
<defs>
|
||||
<radialGradient id="ap-grad" cx="35%" cy="35%" r="70%">
|
||||
<stop offset="0%" stopColor="#ff6b6b" />
|
||||
<stop offset="55%" stopColor="#e11d2e" />
|
||||
<stop offset="100%" stopColor="#a3111f" />
|
||||
</radialGradient>
|
||||
<g id="ap-apple">
|
||||
<path d="M20 10 C20.5 6 22.5 3.5 25.5 2.5" stroke="#78350f" strokeWidth="2.2" fill="none" strokeLinecap="round" />
|
||||
<ellipse cx="27" cy="6" rx="5.5" ry="2.6" fill="#22a447" transform="rotate(-28 27 6)" />
|
||||
<path d="M20 11 C14 6.5 4.5 8.5 4.5 20 C4.5 30 11.5 37.5 20 36 C28.5 37.5 35.5 30 35.5 20 C35.5 8.5 26 6.5 20 11 Z" fill="url(#ap-grad)" stroke="#8f1020" strokeWidth="1.2" />
|
||||
<ellipse cx="12.5" cy="17" rx="3" ry="5" fill="#fff" opacity=".32" />
|
||||
</g>
|
||||
</defs>
|
||||
);
|
||||
}
|
||||
|
||||
function AppleCell({ x, y, n, introDelay }: { x: number; y: number; n: number; introDelay?: number }) {
|
||||
const apple = (
|
||||
<>
|
||||
<use href="#ap-apple" />
|
||||
<text x="20" y="29" textAnchor="middle" fontSize="17" fontWeight="900" fill="#fff" stroke="#6b0b16" strokeWidth="0.8" paintOrder="stroke">
|
||||
{n}
|
||||
</text>
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<g transform={`translate(${x} ${y})`}>
|
||||
{/* The CSS animation goes on an inner group: it would replace the SVG translate on the outer one. */}
|
||||
{introDelay === undefined ? apple : <g className="ap-in" style={{ '--d': `${introDelay}ms` } as CSSProperties}>{apple}</g>}
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
/** Small stand-alone apple for the rules and options (own defs). */
|
||||
function AppleIcon({ n, size = 34 }: { n: number; size?: number }) {
|
||||
return (
|
||||
<svg viewBox="0 0 40 40" width={size} height={size} aria-hidden style={{ verticalAlign: 'middle' }}>
|
||||
<path d="M20 10 C20.5 6 22.5 3.5 25.5 2.5" stroke="#78350f" strokeWidth="2.2" fill="none" strokeLinecap="round" />
|
||||
<ellipse cx="27" cy="6" rx="5.5" ry="2.6" fill="#22a447" transform="rotate(-28 27 6)" />
|
||||
<path d="M20 11 C14 6.5 4.5 8.5 4.5 20 C4.5 30 11.5 37.5 20 36 C28.5 37.5 35.5 30 35.5 20 C35.5 8.5 26 6.5 20 11 Z" fill="#e11d2e" stroke="#8f1020" strokeWidth="1.2" />
|
||||
<text x="20" y="29" textAnchor="middle" fontSize="17" fontWeight="900" fill="#fff">
|
||||
{n}
|
||||
</text>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function useNarrow(): boolean {
|
||||
const q = '(max-width: 640px)';
|
||||
const [m, setM] = useState(() => typeof window !== 'undefined' && window.matchMedia(q).matches);
|
||||
useEffect(() => {
|
||||
const mq = window.matchMedia(q);
|
||||
const on = () => setM(mq.matches);
|
||||
mq.addEventListener('change', on);
|
||||
return () => mq.removeEventListener('change', on);
|
||||
}, []);
|
||||
return m;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
interface Pop {
|
||||
key: number;
|
||||
cells: { i: number; n: number }[];
|
||||
}
|
||||
|
||||
function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
|
||||
const now = useServerNow(200);
|
||||
const phone = useNarrow();
|
||||
const [drag, setDrag] = useState<{ a: Cell; b: Cell } | null>(null);
|
||||
const [cursor, setCursor] = useState<Cell>([0, 0]);
|
||||
const [focused, setFocused] = useState(false);
|
||||
const [gone, setGone] = useState<number[]>([]);
|
||||
const [pops, setPops] = useState<Pop[]>([]);
|
||||
const [flash, setFlash] = useState<{ key: number; ok: boolean; text: string } | null>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const dragRef = useRef(drag);
|
||||
dragRef.current = drag;
|
||||
const seq = useRef(0);
|
||||
|
||||
const mine = v.seats.find((s) => s.id === me) ?? null;
|
||||
const canPlay = !!mine && mine.status === 'playing' && v.phase === 'playing' && !!v.cells && (v.endsAt === null || now < v.endsAt);
|
||||
const unlimited = v.endsAt === null;
|
||||
const [stopAsk, setStopAsk] = useState(false);
|
||||
// The board appearing (after the countdown, or when I open the room) pops the apples in, row by row.
|
||||
const [intro, setIntro] = useState(false);
|
||||
const hadCells = useRef<boolean | null>(null);
|
||||
useEffect(() => {
|
||||
const has = !!v.cells;
|
||||
if (hadCells.current === false && has) setIntro(true);
|
||||
hadCells.current = has;
|
||||
}, [v.cells]);
|
||||
useEffect(() => {
|
||||
if (!intro) return;
|
||||
const t = setTimeout(() => setIntro(false), 900);
|
||||
return () => clearTimeout(t);
|
||||
}, [intro]);
|
||||
useEffect(() => {
|
||||
if (!stopAsk) return;
|
||||
const t = setTimeout(() => setStopAsk(false), 3000);
|
||||
return () => clearTimeout(t);
|
||||
}, [stopAsk]);
|
||||
|
||||
// My board as I see it: the server's, minus the apples I just cleared and the server has not confirmed yet.
|
||||
const cells = useMemo(() => {
|
||||
if (!v.cells) return null;
|
||||
if (!gone.length) return v.cells;
|
||||
const a = v.cells.split('');
|
||||
for (const i of gone) a[i] = '0';
|
||||
return a.join('');
|
||||
}, [v.cells, gone]);
|
||||
|
||||
useEffect(() => {
|
||||
setGone((g) => (g.length ? g.filter((i) => v.cells?.[i] !== '0' && v.cells !== null) : g));
|
||||
}, [v.cells]);
|
||||
// A refused select (too fast, time over): show the apples again.
|
||||
useEffect(() => socket.subscribe((m) => m.t === 'reject' && setGone([])), []);
|
||||
useEffect(() => {
|
||||
if (!canPlay) setDrag(null);
|
||||
}, [canPlay]);
|
||||
useEffect(() => {
|
||||
if (!pops.length) return;
|
||||
const t = setTimeout(() => setPops((p) => p.slice(1)), 450);
|
||||
return () => clearTimeout(t);
|
||||
}, [pops]);
|
||||
useEffect(() => {
|
||||
if (!flash) return;
|
||||
const t = setTimeout(() => setFlash(null), 900);
|
||||
return () => clearTimeout(t);
|
||||
}, [flash]);
|
||||
|
||||
const dR = phone ? COLS : ROWS;
|
||||
const dC = phone ? ROWS : COLS;
|
||||
const toDisp = (c: Cell): Cell => (phone ? [c[1], ROWS - 1 - c[0]] : c);
|
||||
const toCanon = (dr: number, dc: number): Cell => (phone ? [ROWS - 1 - dc, dr] : [dr, dc]);
|
||||
|
||||
const cellAt = (e: { clientX: number; clientY: number }): Cell => {
|
||||
const box = svgRef.current!.getBoundingClientRect();
|
||||
const dc = clamp(Math.floor(((e.clientX - box.left) / box.width) * dC), 0, dC - 1);
|
||||
const dr = clamp(Math.floor(((e.clientY - box.top) / box.height) * dR), 0, dR - 1);
|
||||
return toCanon(dr, dc);
|
||||
};
|
||||
|
||||
const sel = drag && cells ? inside(cells, rectOf(drag.a, drag.b)) : null;
|
||||
const say = (t: string) => setAnnounce(t);
|
||||
|
||||
const finish = (a: Cell, b: Cell, fromKey: boolean) => {
|
||||
if (!cells || !canPlay) return;
|
||||
const rect = rectOf(a, b);
|
||||
const { sum, idx } = inside(cells, rect);
|
||||
if (idx.length === 0) {
|
||||
if (fromKey) say('고른 칸에 사과가 없어요.');
|
||||
return;
|
||||
}
|
||||
if (sum !== 10) {
|
||||
if (idx.length >= 2 || fromKey) {
|
||||
apSound.miss();
|
||||
setFlash({ key: ++seq.current, ok: false, text: `합 ${sum} · 10이 아니에요` });
|
||||
say(`합이 ${sum}이에요. 딱 10이 되게 골라 주세요.`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
act({ type: 'select', ...rect });
|
||||
setGone((g) => [...g, ...idx]);
|
||||
setPops((p) => [...p, { key: ++seq.current, cells: idx.map((i) => ({ i, n: cells.charCodeAt(i) - 48 })) }]);
|
||||
setFlash({ key: ++seq.current, ok: true, text: `+${idx.length}` });
|
||||
apSound.clear(idx.length);
|
||||
haptic(15);
|
||||
say(`사과 ${idx.length}개를 지웠어요.`);
|
||||
};
|
||||
|
||||
const onDown = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
if (!canPlay || (e.pointerType === 'mouse' && e.button !== 0)) return;
|
||||
e.preventDefault();
|
||||
e.currentTarget.setPointerCapture?.(e.pointerId);
|
||||
const c = cellAt(e);
|
||||
setDrag({ a: c, b: c });
|
||||
setCursor(c);
|
||||
};
|
||||
const onMove = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
const d = dragRef.current;
|
||||
if (!d) return;
|
||||
const c = cellAt(e);
|
||||
if (c[0] !== d.b[0] || c[1] !== d.b[1]) setDrag({ a: d.a, b: c });
|
||||
};
|
||||
const onUp = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
const d = dragRef.current;
|
||||
if (!d) return;
|
||||
const c = cellAt(e);
|
||||
setDrag(null);
|
||||
setCursor(c);
|
||||
finish(d.a, c, false);
|
||||
};
|
||||
|
||||
const describe = (c: Cell) => {
|
||||
const [dr, dc] = toDisp(c);
|
||||
const n = cells ? cells.charCodeAt(c[0] * COLS + c[1]) - 48 : 0;
|
||||
return `${dr + 1}줄 ${dc + 1}칸, ${n > 0 ? `사과 ${n}` : '빈 칸'}`;
|
||||
};
|
||||
const onKey = (e: ReactKeyboardEvent<SVGSVGElement>) => {
|
||||
const step: Record<string, Cell> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] };
|
||||
const m = step[e.key];
|
||||
if (m) {
|
||||
e.preventDefault();
|
||||
const [dr, dc] = toDisp(cursor);
|
||||
const next = toCanon(clamp(dr + m[0], 0, dR - 1), clamp(dc + m[1], 0, dC - 1));
|
||||
setCursor(next);
|
||||
if (drag) {
|
||||
setDrag({ a: drag.a, b: next });
|
||||
const s = cells ? inside(cells, rectOf(drag.a, next)).sum : 0;
|
||||
say(`${describe(next)}. 고른 합 ${s}${s === 10 ? ', 지금 누르면 지워져요' : ''}`);
|
||||
} else say(describe(next));
|
||||
return;
|
||||
}
|
||||
if (e.key === ' ' || e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (!canPlay || e.repeat) return;
|
||||
if (!drag) {
|
||||
setDrag({ a: cursor, b: cursor });
|
||||
say('시작점을 정했어요. 화살표로 끝점까지 옮긴 뒤 다시 눌러요.');
|
||||
} else {
|
||||
setDrag(null);
|
||||
finish(drag.a, cursor, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (e.key === 'Escape' && drag) {
|
||||
e.preventDefault();
|
||||
setDrag(null);
|
||||
say('고르기를 취소했어요.');
|
||||
}
|
||||
};
|
||||
|
||||
const left = v.endsAt === null ? null : Math.max(0, v.endsAt - Math.max(now, v.countdownEndsAt));
|
||||
const countdown = v.phase === 'countdown' ? Math.max(1, Math.ceil((v.countdownEndsAt - now) / 1000)) : 0;
|
||||
const sumState = !sel || sel.idx.length === 0 ? 'idle' : sel.sum === 10 ? 'ok' : sel.sum > 10 ? 'over' : 'under';
|
||||
// Sounds that follow the clock and the state: 3·2·1, start, last 10 seconds, "10!" while dragging, finished.
|
||||
const lastSec = v.phase === 'playing' && left !== null && left > 0 && left <= 10_000 ? Math.ceil(left / 1000) : 0;
|
||||
const heard = useRef({ countdown: 0, lastSec: 0, sum: 'idle', status: mine?.status ?? null });
|
||||
useEffect(() => {
|
||||
const was = heard.current;
|
||||
if (countdown !== was.countdown) {
|
||||
if (countdown > 0) apSound.count();
|
||||
else if (was.countdown > 0 && v.phase === 'playing') apSound.go();
|
||||
}
|
||||
if (lastSec && lastSec !== was.lastSec) sfx.tick();
|
||||
if (sumState === 'ok' && was.sum !== 'ok') apSound.ten();
|
||||
const st = mine?.status ?? null;
|
||||
if (st !== was.status && was.status === 'playing' && (st === 'stuck' || st === 'done') && v.phase === 'playing') sfx.good();
|
||||
heard.current = { countdown, lastSec, sum: sumState, status: st };
|
||||
});
|
||||
const others = ranked(v.seats);
|
||||
|
||||
// Selection rectangle in display coordinates.
|
||||
let selBox: ReactNode = null;
|
||||
if (drag) {
|
||||
const [ar, ac] = toDisp(drag.a);
|
||||
const [br, bc] = toDisp(drag.b);
|
||||
const color = sumState === 'ok' ? '#16a34a' : sumState === 'over' ? '#dc2626' : '#2563eb';
|
||||
const fill = sumState === 'ok' ? 'rgba(22,163,74,.28)' : sumState === 'over' ? 'rgba(220,38,38,.16)' : 'rgba(37,99,235,.16)';
|
||||
selBox = (
|
||||
<rect
|
||||
x={Math.min(ac, bc) * S + 1.5}
|
||||
y={Math.min(ar, br) * S + 1.5}
|
||||
width={(Math.abs(ac - bc) + 1) * S - 3}
|
||||
height={(Math.abs(ar - br) + 1) * S - 3}
|
||||
rx={7}
|
||||
fill={fill}
|
||||
stroke={color}
|
||||
strokeWidth={3}
|
||||
pointerEvents="none"
|
||||
/>
|
||||
);
|
||||
}
|
||||
const [cr, cc] = toDisp(cursor);
|
||||
|
||||
return (
|
||||
<div className="ap">
|
||||
<style>{CSS}</style>
|
||||
<div className="ap-top">
|
||||
{left === null ? (
|
||||
<span className="ap-pill" aria-label="제한 시간 없음">
|
||||
⏱ 무제한
|
||||
</span>
|
||||
) : (
|
||||
<span className={`ap-pill${v.phase === 'playing' && left <= 10_000 ? ' warn' : ''}`} role="timer" aria-label={`남은 시간 ${Math.floor(Math.ceil(left / 1000) / 60)}분 ${Math.ceil(left / 1000) % 60}초`}>
|
||||
⏱ {clock(left)}
|
||||
</span>
|
||||
)}
|
||||
{mine && (
|
||||
<span className="ap-pill" aria-label={`내 점수 사과 ${mine.score}개`}>
|
||||
🍎{' '}
|
||||
<b key={mine.score} className={mine.score ? 'anim-bump' : undefined}>
|
||||
{mine.score}
|
||||
</b>
|
||||
</span>
|
||||
)}
|
||||
{mine && v.phase !== 'ended' && (
|
||||
<span className="ap-pill sum" data-s={sumState} aria-hidden>
|
||||
합 {sel && sel.idx.length ? sel.sum : '-'} / 10
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{v.seats.length > 1 && (
|
||||
<ol className="ap-others" aria-label="점수">
|
||||
{others.map((s) => (
|
||||
<li key={s.id} data-me={s.id === me} data-out={s.status === 'left'} aria-label={`${s.rank}등 ${nick(players, s.id)}${s.id === me ? '(나)' : ''} 사과 ${s.score}개${statusSuffix(s)}`}>
|
||||
<Avatar user={userOf(players, s.id)} size={20} />
|
||||
<span>{s.id === me ? '나' : nick(players, s.id)}</span>
|
||||
<b key={s.score} className={s.score ? 'anim-bump' : undefined}>
|
||||
{s.score}
|
||||
</b>
|
||||
{(s.status === 'stuck' || s.status === 'done') && <span aria-hidden>✔</span>}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
<div className="ap-wrap" data-phone={phone}>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
className="ap-board"
|
||||
data-off={!canPlay}
|
||||
viewBox={`0 0 ${dC * S} ${dR * S}`}
|
||||
role="application"
|
||||
aria-roledescription="사과 판"
|
||||
aria-label={
|
||||
canPlay
|
||||
? `사과 판 ${dR}줄 ${dC}칸. 화살표로 칸을 옮기고 스페이스나 Enter로 시작점과 끝점을 정해요. 지금 ${describe(cursor)}`
|
||||
: '사과 판'
|
||||
}
|
||||
tabIndex={0}
|
||||
onPointerDown={onDown}
|
||||
onPointerMove={onMove}
|
||||
onPointerUp={onUp}
|
||||
onPointerCancel={() => setDrag(null)}
|
||||
onKeyDown={onKey}
|
||||
onFocus={() => setFocused(true)}
|
||||
onBlur={() => setFocused(false)}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
<AppleDefs />
|
||||
{cells &&
|
||||
Array.from(cells, (ch, i) => {
|
||||
const n = ch.charCodeAt(0) - 48;
|
||||
if (n <= 0) return null;
|
||||
const [dr, dc] = toDisp([Math.floor(i / COLS), i % COLS]);
|
||||
return <AppleCell key={i} x={dc * S} y={dr * S} n={n} introDelay={intro ? (dr + dc) * 14 : undefined} />;
|
||||
})}
|
||||
{pops.map((p) =>
|
||||
p.cells.map(({ i, n }) => {
|
||||
const [dr, dc] = toDisp([Math.floor(i / COLS), i % COLS]);
|
||||
return (
|
||||
<g key={`${p.key}-${i}`}>
|
||||
<circle className="ap-burst" cx={dc * S + 20} cy={dr * S + 21} r={17} fill="none" stroke="#f87171" strokeWidth={4} />
|
||||
<g className="ap-pop">
|
||||
<AppleCell x={dc * S} y={dr * S} n={n} />
|
||||
</g>
|
||||
</g>
|
||||
);
|
||||
}),
|
||||
)}
|
||||
{selBox}
|
||||
{focused && canPlay && <rect x={cc * S + 2} y={cr * S + 2} width={S - 4} height={S - 4} rx={8} fill="none" stroke="#f59e0b" strokeWidth={3} strokeDasharray="5 3" pointerEvents="none" />}
|
||||
</svg>
|
||||
{flash && (
|
||||
<div key={flash.key} className={`ap-flash ${flash.ok ? 'ok' : 'bad'}`} aria-hidden>
|
||||
{flash.text}
|
||||
</div>
|
||||
)}
|
||||
{countdown > 0 && (
|
||||
<div className="ap-over count" aria-hidden>
|
||||
<b key={countdown}>{countdown}</b>
|
||||
<small>합이 10이 되게 사과를 묶어요!</small>
|
||||
</div>
|
||||
)}
|
||||
{mine && mine.status === 'stuck' && v.phase === 'playing' && (
|
||||
<div className="ap-over note" role="status">
|
||||
더 지울 수 있는 사과가 없어요! 사과 {mine.score}개 · 끝날 때까지 기다려요
|
||||
</div>
|
||||
)}
|
||||
{mine && mine.status === 'done' && v.phase === 'playing' && (
|
||||
<div className="ap-over note" role="status">
|
||||
여기까지 했어요! 사과 {mine.score}개 · 모두 끝날 때까지 기다려요
|
||||
</div>
|
||||
)}
|
||||
{mine && mine.status === 'left' && v.phase !== 'ended' && <div className="ap-over note">게임에서 나갔어요.</div>}
|
||||
{!mine && v.phase !== 'ended' && <div className="ap-over note">관전 중이에요 · 위에서 점수를 볼 수 있어요</div>}
|
||||
</div>
|
||||
{unlimited && canPlay && (
|
||||
<button
|
||||
type="button"
|
||||
className={`btn ${stopAsk ? 'btn-primary' : 'btn-secondary'} ap-stop`}
|
||||
onClick={() => {
|
||||
if (!stopAsk) return setStopAsk(true);
|
||||
setStopAsk(false);
|
||||
act({ type: 'stop' });
|
||||
}}
|
||||
>
|
||||
{stopAsk ? '한 번 더 누르면 여기까지 해요' : `여기까지 할래요 (사과 ${mine.score}개)`}
|
||||
</button>
|
||||
)}
|
||||
{!phone && mine && v.phase !== 'ended' && <p className="ap-keys">마우스로 드래그해서 합이 10이면 손을 떼요 · 키보드: 화살표 + 스페이스(시작점·끝점), Esc 취소</p>}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function AppleSide({ view: v, me, players }: BoardProps<AppleView>) {
|
||||
const rows = ranked(v.seats);
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<strong>사과 게임{v.phase === 'ended' ? ' · 게임 끝' : ''}</strong>
|
||||
<span className="small muted">17×10 판 · 제한 시간 {limitLabel(v.options.timeLimitSec)}{v.options.timeLimitSec === null ? '(모두 끝낼 때까지)' : ''} · 모두 같은 판</span>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||
{rows.map((s) => (
|
||||
<li
|
||||
key={s.id}
|
||||
className="row"
|
||||
style={{ gap: 6, flexWrap: 'nowrap', opacity: s.status === 'left' ? 0.55 : 1 }}
|
||||
aria-label={`${s.rank}등 ${nick(players, s.id)}${s.id === me ? '(나)' : ''}, 사과 ${s.score}개, ${s.clears}번 지움${statusSuffix(s)}`}
|
||||
>
|
||||
<span aria-hidden style={{ width: 28, fontWeight: 800 }}>
|
||||
{s.rank}등
|
||||
</span>
|
||||
<Avatar user={userOf(players, s.id)} size={24} />
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: s.id === me ? 800 : 600 }} aria-hidden>
|
||||
{nick(players, s.id)}
|
||||
{s.id === me ? ' (나)' : ''}
|
||||
{s.status === 'stuck' ? ' · 다 지움' : s.status === 'done' ? ' · 여기까지' : s.status === 'left' ? ' · 나감' : ''}
|
||||
</span>
|
||||
<strong style={{ fontVariantNumeric: 'tabular-nums' }} aria-hidden>
|
||||
🍎 {s.score}
|
||||
</strong>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
<span key={r.id}>
|
||||
{r.rank}등 {nick(players, r.id)}
|
||||
<span className="muted small">
|
||||
{' '}
|
||||
· 사과 {r.score}개 · {r.clears}번{r.left ? ' · 나감' : ''}
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- status
|
||||
|
||||
function isMyTurn(v: AppleView, me: string | null): boolean {
|
||||
return !!me && v.phase === 'playing' && v.seats.some((s) => s.id === me && s.status === 'playing');
|
||||
}
|
||||
|
||||
function statusText(v: AppleView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
if (v.phase === 'ended') return v.result?.summary ?? '게임이 끝났어요';
|
||||
if (v.phase === 'countdown') return '곧 시작해요! 합이 10이 되게 사과를 드래그해요';
|
||||
const mine = v.seats.find((s) => s.id === me);
|
||||
if (!mine) {
|
||||
const top = ranked(v.seats)[0];
|
||||
return top && top.score > 0 ? `${nick(players, top.id)}님이 사과 ${top.score}개로 앞서요` : '모두 같은 판을 풀고 있어요';
|
||||
}
|
||||
if (mine.status === 'left') return '게임에서 나갔어요';
|
||||
if (mine.status === 'stuck') return `더 지울 사과가 없어요 · 사과 ${mine.score}개 · 끝날 때까지 기다려요`;
|
||||
if (mine.status === 'done') return `여기까지 했어요 · 사과 ${mine.score}개 · 모두 끝날 때까지 기다려요`;
|
||||
return `사과 ${mine.score}개 지웠어요 · 합이 10이 되게 드래그!`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
return (
|
||||
<div className="segmented" role="group" aria-label={label}>
|
||||
{options.map(([k, l]) => (
|
||||
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<AppleOptions>) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>제한 시간</strong>
|
||||
<Seg
|
||||
label="제한 시간"
|
||||
value={o.timeLimitSec}
|
||||
options={[
|
||||
[60, '1분'],
|
||||
[120, '2분'],
|
||||
[180, '3분'],
|
||||
[null, '무제한'],
|
||||
]}
|
||||
onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec })}
|
||||
/>
|
||||
<span className="small muted">
|
||||
{o.timeLimitSec === null
|
||||
? '시간 제한 없이 각자 더 지울 사과가 없거나 [여기까지 할래요]를 누를 때까지 해요. 모두 끝나면 가장 많이 지운 사람이 이겨요.'
|
||||
: '원래 게임은 2분이에요. 시간이 끝났을 때 사과를 가장 많이 지운 사람이 이겨요.'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: AppleOptions): string {
|
||||
return `제한 시간 ${limitLabel(o.timeLimitSec)} · 17×10 판`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- rules
|
||||
|
||||
function Rules({ options }: { options?: AppleOptions }) {
|
||||
const limitSec = options ? options.timeLimitSec : 120;
|
||||
const limit = limitLabel(limitSec);
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
가로 17칸, 세로 10줄 판에 1부터 9까지 숫자가 적힌 사과 170개가 가득 놓여 있어요. 모두 <strong>똑같은 판</strong>을 각자 자기 화면에서 동시에 풀어요.
|
||||
</p>
|
||||
<div className="row" style={{ gap: 4, alignItems: 'center' }}>
|
||||
<AppleIcon n={3} />
|
||||
<AppleIcon n={4} />
|
||||
<AppleIcon n={3} />
|
||||
<span>= 10 → 사과 3개가 사라지고 3점!</span>
|
||||
</div>
|
||||
<p>
|
||||
사과들을 <strong>직사각형으로 드래그</strong>해서 그 안의 숫자 합이 <strong>딱 10</strong>이면 손을 뗐을 때 사과가 사라지고, 사라진 개수만큼 점수를 얻어요. 합이 10이 아니면 아무 일도
|
||||
일어나지 않고 벌칙도 없어요. 지운 자리는 빈 칸이 되고 빈 칸은 합에 들어가지 않아서, 사이가 비면 멀리 있는 사과끼리도 묶을 수 있어요.
|
||||
</p>
|
||||
<p>
|
||||
{limitSec === null
|
||||
? '이 방은 제한 시간이 없어요. 각자 더 지울 수 있는 묶음이 없거나 [여기까지 할래요]를 누르면 끝나고, 모두 끝나면 사과를 가장 많이 지운 사람이 이겨요. 개수가 같으면 같은 순위예요. 연결이 끊긴 채 오래 돌아오지 않으면 그때까지 점수로 끝낸 것으로 봐요.'
|
||||
: `제한 시간은 ${limit}이에요. 시간이 끝나면 사과를 가장 많이 지운 사람이 이기고, 개수가 같으면 같은 순위예요. 모두 더 지울 수 있는 묶음이 없으면 조금 일찍 끝나요.`}{' '}
|
||||
혼자서도 할 수 있어요.
|
||||
</p>
|
||||
<p>
|
||||
휴대폰에서는 판을 세로로 돌려서 보여 줘요. 키보드로는 화살표로 칸을 옮기고 <strong>스페이스</strong>(또는 Enter)로 시작점, 한 번 더 눌러 끝점을 정해요. <strong>Esc</strong>는 취소예요.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<AppleView, AppleOptions> = {
|
||||
Board: AppleBoard,
|
||||
Side: AppleSide,
|
||||
statusText,
|
||||
isMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
81
apps/web/src/games/apple/quick.tsx
Normal file
@@ -0,0 +1,81 @@
|
||||
/** 사과 게임 30초 규칙 요약 (docs/07 §5). Simple redraws of the board apples. */
|
||||
import type { ReactNode } from 'react';
|
||||
import type { QuickCard } from '../types';
|
||||
|
||||
/** One apple with its number, centred at (x, y), about 26 units wide. */
|
||||
function Apple({ x, y, n, dim = false }: { x: number; y: number; n: number; dim?: boolean }) {
|
||||
return (
|
||||
<g transform={`translate(${x} ${y})`} opacity={dim ? 0.3 : 1}>
|
||||
<path d="M0 -11 C1 -15 3 -17 5 -18" stroke="#78350f" strokeWidth={2} fill="none" strokeLinecap="round" />
|
||||
<ellipse cx={5} cy={-15} rx={4.5} ry={2.2} fill="#16a34a" transform="rotate(-25 5 -15)" />
|
||||
<circle cx={0} cy={2} r={12} fill="#dc2626" stroke="#991b1b" strokeWidth={1.5} />
|
||||
<text x={0} y={7.5} textAnchor="middle" fontSize={15} fontWeight={900} fill="#fff">
|
||||
{n}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
function Frame({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<svg viewBox="0 0 240 150" width={240} height={150} aria-hidden>
|
||||
<rect x={0} y={0} width={240} height={150} rx={14} fill="#fef3c7" />
|
||||
{children}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
const ROW1 = [3, 7, 5, 2, 8, 1, 6];
|
||||
const ROW2 = [4, 1, 5, 9, 2, 2, 6];
|
||||
const ROW3 = [6, 2, 8, 1, 3, 9, 4];
|
||||
|
||||
function Grid({ gone = [] as number[] }) {
|
||||
return (
|
||||
<>
|
||||
{[ROW1, ROW2, ROW3].map((row, r) =>
|
||||
row.map((n, c) => <Apple key={`${r}-${c}`} x={30 + c * 30} y={36 + r * 38} n={n} dim={gone.includes(r * 7 + c)} />),
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: (
|
||||
<Frame>
|
||||
<Grid />
|
||||
</Frame>
|
||||
),
|
||||
alt: '숫자 1부터 9가 적힌 빨간 사과가 줄지어 놓인 판이에요',
|
||||
title: '모두 같은 판을 풀어요',
|
||||
text: '숫자가 적힌 사과 판이 나와요. 모두 똑같은 판을 각자 자기 화면에서 동시에 풀어요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<Frame>
|
||||
<Grid />
|
||||
<rect x={14} y={18} width={62} height={36} rx={6} fill="rgba(22,163,74,.25)" stroke="#16a34a" strokeWidth={3} />
|
||||
<text x={200} y={140} textAnchor="middle" fontSize={16} fontWeight={900} fill="#15803d">
|
||||
3+7=10!
|
||||
</text>
|
||||
</Frame>
|
||||
),
|
||||
alt: '3과 7이 적힌 사과 두 개를 초록 네모로 묶은 모습이에요. 합이 10이에요',
|
||||
title: '합이 10이면 사라져요',
|
||||
text: '사과를 직사각형으로 드래그해서 숫자 합이 딱 10이면 손을 떼요. 사과가 사라지고 개수만큼 점수예요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<Frame>
|
||||
<Grid gone={[0, 1, 7, 14, 2, 9]} />
|
||||
<rect x={150} y={8} width={82} height={26} rx={13} fill="#1f2937" />
|
||||
<text x={191} y={26} textAnchor="middle" fontSize={15} fontWeight={800} fill="#fff">
|
||||
⏱ 1:42
|
||||
</text>
|
||||
</Frame>
|
||||
),
|
||||
alt: '몇 개의 사과가 지워져 흐려졌고, 오른쪽 위에 남은 시간 1분 42초가 보여요',
|
||||
title: '2분 동안 많이 지우기',
|
||||
text: '빈 칸은 합에 안 들어가요. 시간이 끝났을 때 사과를 가장 많이 지운 사람이 이겨요.',
|
||||
},
|
||||
];
|
||||
@@ -4,7 +4,8 @@ import type { BadukOptions, BadukView, Pt, ScoreBreakdown } from '@bg/games/badu
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
|
||||
import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { BOARD_MOTION_CSS, useAnimOver, useMoveDiff } from '../board-motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -35,9 +36,18 @@ function fmtScore(n: number, method: 'territory' | 'area'): string {
|
||||
return half ? (whole === 0 ? '반' : `${whole}.5`) : String(whole);
|
||||
}
|
||||
|
||||
/** Stones taken off the board: a few small clicks as they are picked up into the lid. */
|
||||
function captureSound(count: number) {
|
||||
for (let k = 0; k < Math.min(count, 6); k++) {
|
||||
tone(2100 + (k % 3) * 260, 28, 'triangle', 0.06, 150 + k * 55);
|
||||
noise(25, 0.05, 150 + k * 55, 'highpass', 4500);
|
||||
}
|
||||
}
|
||||
|
||||
function Stone({ color, cx, cy, r, ghost }: { color: Color; cx: number; cy: number; r: number; ghost?: boolean }) {
|
||||
return (
|
||||
<g opacity={ghost ? 0.5 : 1}>
|
||||
{!ghost && <ellipse cx={cx + r * 0.1} cy={cy + r * 0.16} rx={r} ry={r * 0.96} fill="#000" opacity={0.22} />}
|
||||
<circle cx={cx} cy={cy} r={r} fill={color === 'black' ? '#151515' : '#fbfbf8'} stroke={color === 'black' ? '#000' : '#666'} strokeWidth={0.05} />
|
||||
{color === 'black' ? (
|
||||
<circle cx={cx - r * 0.3} cy={cy - r * 0.3} r={r * 0.28} fill="#fff" opacity={0.15} />
|
||||
@@ -76,21 +86,33 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
return out;
|
||||
}, [v.scoring, v.result, v.board, n]);
|
||||
const seki = useMemo(() => new Set((v.scoring?.seki ?? []).map((p) => p.y * n + p.x)), [v.scoring?.seki, n]);
|
||||
// Board before the last move: the new stone sets down and captures fade only for moves seen live;
|
||||
// 무르기 lifts the taken-back stone and puts captured stones back.
|
||||
const { before, forward } = useMoveDiff(v.board, v.moveCount);
|
||||
const fresh = !!before && forward;
|
||||
const undone = before && !forward ? before.flatMap((c, i) => (c !== 0 && v.board[i] === 0 ? [{ i, color: (c === 1 ? 'black' : 'white') as Color }] : [])) : [];
|
||||
const [goneOver, goneEnd] = useAnimOver(v.moveCount);
|
||||
const restored = new Set(before && !forward ? v.board.flatMap((c, i) => (c !== 0 && before[i] === 0 ? [i] : [])) : []);
|
||||
|
||||
// Move sounds and announcements.
|
||||
// Move sounds and announcements (mine, the opponent's and the computer's).
|
||||
useEffect(() => {
|
||||
if (v.moveCount > prevCount.current) {
|
||||
const m = v.moves[v.moves.length - 1]!;
|
||||
if (m.pt) {
|
||||
sounds.stone();
|
||||
if (m.captured > 0) haptic(30);
|
||||
sfx.stone();
|
||||
if (m.captured > 0) {
|
||||
captureSound(m.captured);
|
||||
haptic(30);
|
||||
}
|
||||
setAnnounce(`${COLOR_KO[m.color]}이 ${label(n, m.pt)}에 두었어요.${m.captured ? ` 돌 ${m.captured}개를 따냈어요.` : ''}`);
|
||||
} else setAnnounce(`${COLOR_KO[m.color]}이 패스했어요.`);
|
||||
if (myTurn) {
|
||||
haptic(40);
|
||||
if (document.visibilityState === 'hidden') sounds.myTurn();
|
||||
} else {
|
||||
// 패스: a soft knock on the board edge.
|
||||
tone(330, 90, 'sine', 0.1);
|
||||
noise(50, 0.05, 0, 'lowpass', 700);
|
||||
setAnnounce(`${COLOR_KO[m.color]}이 패스했어요.`);
|
||||
}
|
||||
}
|
||||
if (myTurn) haptic(40);
|
||||
} else if (v.moveCount < prevCount.current) sfx.whoosh();
|
||||
prevCount.current = v.moveCount;
|
||||
setPreview(null);
|
||||
setBubble(null);
|
||||
@@ -109,6 +131,7 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
for (const i of dead) if (!before.has(i)) diff.add(i);
|
||||
for (const i of before) if (!dead.has(i)) diff.add(i);
|
||||
if (diff.size === 0) return;
|
||||
sfx.click();
|
||||
setChanged(diff);
|
||||
const t = setTimeout(() => setChanged(new Set()), 2500);
|
||||
return () => clearTimeout(t);
|
||||
@@ -142,6 +165,7 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
const why = illegal.get(p.y * n + p.x);
|
||||
if (why) {
|
||||
haptic([30, 30, 30]);
|
||||
sfx.bad();
|
||||
setBubble({ p, text: ILLEGAL_KO[why] });
|
||||
setAnnounce(ILLEGAL_KO[why]);
|
||||
return;
|
||||
@@ -186,6 +210,7 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
const pad = 0.95;
|
||||
return (
|
||||
<div className="board-wrap stack" style={{ gap: 10 }}>
|
||||
<style>{BOARD_MOTION_CSS}</style>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
viewBox={`${-pad} ${-pad} ${n - 1 + 2 * pad} ${n - 1 + 2 * pad}`}
|
||||
@@ -242,20 +267,35 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
const x = i % n;
|
||||
const y = Math.floor(i / n);
|
||||
const isDead = dead.has(i);
|
||||
const isLast = fresh && v.lastMove !== null && i === v.lastMove.y * n + v.lastMove.x;
|
||||
return (
|
||||
<g key={i} opacity={isDead ? 0.45 : 1}>
|
||||
<Stone color={color} cx={x} cy={y} r={0.47} />
|
||||
<g key={isLast ? `m${v.moveCount}` : i} opacity={isDead ? 0.45 : 1} style={{ transition: 'opacity 0.25s' }}>
|
||||
<g className={isLast ? 'bm-place' : restored.has(i) ? 'anim-pop' : undefined}>
|
||||
<Stone color={color} cx={x} cy={y} r={0.47} />
|
||||
</g>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{/* Stones just captured fade out. */}
|
||||
{v.phase === 'playing' &&
|
||||
v.lastCaptured.map((p) => (
|
||||
<g key={`cap${v.moveCount}-${p.x}-${p.y}`} opacity={0}>
|
||||
<animate attributeName="opacity" from={0.7} to={0} dur="0.6s" fill="freeze" />
|
||||
{/* Stones just captured are lifted off one by one; a stone taken back by 무르기 fades. */}
|
||||
{fresh &&
|
||||
!goneOver &&
|
||||
v.phase === 'playing' &&
|
||||
v.lastCaptured.map((p, k, all) => (
|
||||
<g
|
||||
key={`cap${v.moveCount}-${p.x}-${p.y}`}
|
||||
className="bm-gone"
|
||||
style={{ animationDelay: `${150 + Math.min(k, 6) * 55}ms` }}
|
||||
onAnimationEnd={k === all.length - 1 ? goneEnd : undefined}
|
||||
>
|
||||
<Stone color={lastColor ? other(lastColor) : 'white'} cx={p.x} cy={p.y} r={0.47} />
|
||||
</g>
|
||||
))}
|
||||
{!goneOver &&
|
||||
undone.map(({ i, color }) => (
|
||||
<g key={`u${v.moveCount}-${i}`} className="bm-gone" onAnimationEnd={goneEnd}>
|
||||
<Stone color={color} cx={i % n} cy={Math.floor(i / n)} r={0.47} />
|
||||
</g>
|
||||
))}
|
||||
{/* Territory / area marks (small squares) and seki marks. */}
|
||||
{score &&
|
||||
score.ownership.map((o, i) => {
|
||||
@@ -277,7 +317,10 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
</circle>
|
||||
))}
|
||||
{v.lastMove && lastColor && (
|
||||
<circle cx={v.lastMove.x} cy={v.lastMove.y} r={0.2} fill="none" stroke={lastColor === 'black' ? '#fff' : '#111'} strokeWidth={0.08} />
|
||||
<g key={`lm${v.moveCount}`}>
|
||||
{fresh && <circle className="bm-ring" cx={v.lastMove.x} cy={v.lastMove.y} r={0.5} fill="none" stroke={lastColor === 'black' ? '#111' : '#fafafa'} strokeWidth={0.06} />}
|
||||
<circle cx={v.lastMove.x} cy={v.lastMove.y} r={0.2} fill="none" stroke={lastColor === 'black' ? '#fff' : '#111'} strokeWidth={0.08} />
|
||||
</g>
|
||||
)}
|
||||
{myTurn &&
|
||||
v.atariWarnings.map((p) => (
|
||||
@@ -787,7 +830,7 @@ function Options({ value: o, onChange }: OptionsProps<BadukOptions>) {
|
||||
</div>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>사석 확인 제한 시간</strong>
|
||||
<Seg value={o.scoringDeadlineSec} options={[[120, '2분'], [180, '3분'], [300, '5분']]} onChange={(scoringDeadlineSec) => set({ scoringDeadlineSec })} />
|
||||
<Seg value={o.scoringDeadlineSec} options={[[120, '2분'], [180, '3분'], [300, '5분'], [0, '무제한']]} onChange={(scoringDeadlineSec) => set({ scoringDeadlineSec })} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -77,7 +77,7 @@ export function helpNow(v: BangView, me: string | null, players: Record<string,
|
||||
if (use.length >= p.needed) {
|
||||
const label = use.map((c) => NAME[c.kind as 'bang' | 'missed'] ?? '빗나감!').join(' + ');
|
||||
lines.push(`[${label} 내기]를 누르면 막아요. 막지 않으려면 [맞기 (생명 −1)]를 눌러요.`);
|
||||
if (v.options.autoDefend) lines.push('시간 안에 고르지 않으면 막을 카드를 자동으로 내요.');
|
||||
if (v.options.autoDefend) lines.push(v.options.reactionSeconds === null ? '반응 시간 제한은 없어요. 연결이 끊긴 채 오래 돌아오지 않으면 막을 카드를 자동으로 내요.' : '시간 안에 고르지 않으면 막을 카드를 자동으로 내요.');
|
||||
} else lines.push(`막을 카드가 ${p.options.length > 0 ? '모자라요' : '없어요'}. [맞기 (생명 −1)]를 눌러요.`);
|
||||
if (p.canBarrel) lines.push('[술통 판정하기]를 누르면 카드를 한 장 뒤집어 ♥가 나올 때 피해요.');
|
||||
lines.push(life);
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
/** 뱅! 화면 (docs/games/bang.md §9). */
|
||||
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
|
||||
import type { BangOptions, BangView, Card, CardFace, CardKind, CharacterId, LogEntry, PlayOption, PlayerView, Prompt, Role, Team } from '@bg/games/bang';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner, useNewEntries, type BannerTone } from '../card-fx';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -176,14 +177,91 @@ button.bg-card:focus-visible { outline: 3px solid var(--focus); outline-offset:
|
||||
.bg-me { padding: 8px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { button.bg-card { transition: none; } }
|
||||
.fx-ghost.bg-ghost { background: #fffaf0; border: 2px solid #92400e; box-shadow: 0 3px 8px rgba(0,0,0,.35); display: flex; align-items: center; justify-content: center;
|
||||
font: 900 20px/1 system-ui, sans-serif; color: #1f2937; }
|
||||
.fx-ghost.bg-ghost.blue { border-color: #1d4ed8; }
|
||||
.fx-ghost.bg-ghost.chk { font-size: 14px; }
|
||||
.fx-ghost.bg-ghost.chk.r { color: #dc2626; }
|
||||
.fx-ghost.bg-ghost-back { background: repeating-linear-gradient(45deg, #7c2d12 0 5px, #9a3412 5px 10px); border: 2px solid #fdba74; box-shadow: 0 3px 8px rgba(0,0,0,.35); }
|
||||
.fx-ghost.bg-bullet { background: none; border: 0; box-shadow: none; font-size: 22px; }
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------- sounds + motion helpers
|
||||
|
||||
/** 뱅! sounds on top of the shared palette (synthesized; `d` = delay in ms). */
|
||||
const shot = (d = 0) => {
|
||||
noise(110, 0.32, d, 'bandpass', 1700, 0.6);
|
||||
noise(40, 0.18, d, 'highpass', 4500);
|
||||
tone(95, 170, 'sine', 0.26, d, { slideTo: 45 });
|
||||
};
|
||||
const bangSfx = {
|
||||
shot,
|
||||
gatling: (d = 0) => {
|
||||
for (let i = 0; i < 7; i++) {
|
||||
noise(60, 0.22, d + i * 85, 'bandpass', 1600 + (i % 3) * 250, 0.7);
|
||||
tone(90, 80, 'sine', 0.15, d + i * 85, { slideTo: 50 });
|
||||
}
|
||||
},
|
||||
/** 빗나감! / 술통: a ricochet whistle. */
|
||||
ricochet: (d = 0) => {
|
||||
noise(30, 0.08, d, 'highpass', 5000);
|
||||
tone(2200, 300, 'sine', 0.07, d + 10, { slideTo: 700 });
|
||||
},
|
||||
hit: (d = 0) => {
|
||||
noise(90, 0.2, d, 'lowpass', 500, 0.8);
|
||||
tone(160, 200, 'sawtooth', 0.07, d, { slideTo: 70 });
|
||||
},
|
||||
/** Glug glug + clink. */
|
||||
beer: (d = 0) => {
|
||||
[0, 110, 220].forEach((x, i) => tone(240 - i * 25, 80, 'sine', 0.14, d + x, { slideTo: 150 }));
|
||||
tone(2600, 140, 'triangle', 0.05, d + 340);
|
||||
tone(3300, 120, 'triangle', 0.04, d + 360);
|
||||
},
|
||||
boom: (d = 0) => {
|
||||
noise(900, 0.42, d, 'lowpass', 380, 0.7);
|
||||
noise(120, 0.22, d, 'bandpass', 1200, 0.5);
|
||||
tone(70, 800, 'sine', 0.3, d, { slideTo: 28 });
|
||||
},
|
||||
/** Jail bars. */
|
||||
clank: (d = 0) => {
|
||||
tone(330, 180, 'square', 0.05, d);
|
||||
tone(495, 220, 'square', 0.04, d + 30);
|
||||
noise(70, 0.14, d, 'bandpass', 4200, 3);
|
||||
},
|
||||
drums: (d = 0) =>
|
||||
[0, 170, 340, 430, 520].forEach((x) => {
|
||||
tone(120, 130, 'sine', 0.26, d + x, { slideTo: 65 });
|
||||
noise(50, 0.08, d + x, 'lowpass', 320);
|
||||
}),
|
||||
duel: (d = 0) => {
|
||||
shot(d);
|
||||
shot(d + 340);
|
||||
},
|
||||
death: (d = 0) => tone(440, 750, 'triangle', 0.12, d, { slideTo: 100 }),
|
||||
};
|
||||
|
||||
/** 판정 card / role badge turning face up (Web Animations, no layout change). */
|
||||
function flip(el: Element | null | undefined, delay = 0): void {
|
||||
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
|
||||
(el as HTMLElement).animate([{ transform: 'perspective(500px) rotateX(90deg)', opacity: 0.3 }, { transform: 'perspective(500px) rotateX(0deg)', opacity: 1 }], {
|
||||
duration: 380,
|
||||
delay,
|
||||
easing: 'ease-out',
|
||||
fill: 'backwards',
|
||||
composite: 'add',
|
||||
});
|
||||
}
|
||||
|
||||
const sameFace = (a: CardFace, b: CardFace) => a.kind === b.kind && a.suit === b.suit && a.rank === b.rank;
|
||||
const faceGhost = (f: CardFace) => ({ label: CARD_INFO[f.kind].icon, className: `bg-ghost${BLUE.includes(f.kind) ? ' blue' : ''}` });
|
||||
const BACK_GHOST = { className: 'bg-ghost-back' };
|
||||
|
||||
// ---------------------------------------------------------------- small parts
|
||||
|
||||
function CardArt({ card, small, label }: { card: CardFace; small?: boolean; label?: boolean }) {
|
||||
function CardArt({ card, small, label, fx }: { card: CardFace; small?: boolean; label?: boolean; fx?: string }) {
|
||||
const info = CARD_INFO[card.kind];
|
||||
return (
|
||||
<span className={`bg-card${small ? ' sm' : ''}`} data-blue={BLUE.includes(card.kind)} aria-hidden={!label} {...(label ? { role: 'img', 'aria-label': faceAria(card) } : {})}>
|
||||
<span className={`bg-card${small ? ' sm' : ''}`} data-fx={fx} data-blue={BLUE.includes(card.kind)} aria-hidden={!label} {...(label ? { role: 'img', 'aria-label': faceAria(card) } : {})}>
|
||||
<CardFaceInner card={card} info={info} />
|
||||
</span>
|
||||
);
|
||||
@@ -300,7 +378,7 @@ function Seat({
|
||||
) : p.isTurn && !v.reactions.length && !v.winner ? (
|
||||
<TurnTimer deadline={v.turnDeadline} totalMs={v.deadlineTotalMs} mine={p.id === me} size={26} />
|
||||
) : null;
|
||||
const cls = `bg-seat${p.isTurn ? ' turn' : ''}${r ? ' react' : ''}${p.id === me ? ' me' : ''}${!p.alive ? ' dead' : ''}`;
|
||||
const cls = `bg-seat${p.isTurn ? ` turn${v.winner ? '' : ' anim-glow'}` : ''}${r ? ' react' : ''}${p.id === me ? ' me' : ''}${!p.alive ? ' dead' : ''}`;
|
||||
const body = (
|
||||
<>
|
||||
<span className="bg-row nw">
|
||||
@@ -347,6 +425,7 @@ function Seat({
|
||||
style={style}
|
||||
data-target="ok"
|
||||
data-player={p.id}
|
||||
data-fx-seat={p.id}
|
||||
aria-pressed={mark.selected}
|
||||
aria-label={`${seatLabel(p, players, me, shownRole(p, v, me))}. 대상으로 고르기`}
|
||||
onClick={() => onPick(p.id)}
|
||||
@@ -356,7 +435,7 @@ function Seat({
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className={cls} style={style} data-target={mark ? 'no' : undefined} data-player={p.id} role="group" aria-label={seatLabel(p, players, me, shownRole(p, v, me)) + (mark?.reason ? `. ${mark.reason}` : '')}>
|
||||
<div className={cls} style={style} data-target={mark ? 'no' : undefined} data-player={p.id} data-fx-seat={p.id} role="group" aria-label={seatLabel(p, players, me, shownRole(p, v, me)) + (mark?.reason ? `. ${mark.reason}` : '')}>
|
||||
{body}
|
||||
</div>
|
||||
);
|
||||
@@ -379,15 +458,15 @@ function Center({ v, players }: { v: BangView; players: Record<string, PublicUse
|
||||
const last = v.log[v.log.length - 1];
|
||||
return (
|
||||
<div className="bg-center">
|
||||
<div className="bg-piles">
|
||||
<span className="bg-back" role="img" aria-label={`카드 더미 ${v.deckCount}장`}>
|
||||
<div className="bg-piles" data-fx="bang-piles">
|
||||
<span className="bg-back" data-fx="bang-deck" role="img" aria-label={`카드 더미 ${v.deckCount}장`}>
|
||||
{v.deckCount}
|
||||
</span>
|
||||
{top ? <CardArt card={top} small label /> : <span className="bg-chip">버린 카드 없음</span>}
|
||||
{top ? <CardArt card={top} small label fx="bang-discard" /> : <span className="bg-chip" data-fx="bang-discard">버린 카드 없음</span>}
|
||||
</div>
|
||||
{v.phase !== 'draft' && <span className="bg-chip">{v.round}라운드</span>}
|
||||
{chk && (
|
||||
<span className={`bg-chip ${chk.success ? 'ok' : 'bad'}`} aria-live="polite">
|
||||
<span className={`bg-chip ${chk.success ? 'ok' : 'bad'}`} data-fx="bang-check" aria-live="polite">
|
||||
{nick(players, chk.player)}님 {PURPOSE[chk.purpose]} 판정: {chk.cards.map((c) => `${SUIT_SYMBOL[c.suit]}${c.rank}`).join(' · ')} → {chk.success ? '성공' : '실패'}
|
||||
</span>
|
||||
)}
|
||||
@@ -474,12 +553,14 @@ function HandCards({
|
||||
picked,
|
||||
onTap,
|
||||
label,
|
||||
fx,
|
||||
}: {
|
||||
hand: Card[];
|
||||
okOf?: (c: Card) => boolean | undefined;
|
||||
picked: (c: Card) => boolean;
|
||||
onTap: (c: Card) => void;
|
||||
label: string;
|
||||
fx?: string;
|
||||
}) {
|
||||
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
|
||||
@@ -490,7 +571,7 @@ function HandCards({
|
||||
btns[(i + (e.key === 'ArrowRight' ? 1 : btns.length - 1)) % btns.length]?.focus();
|
||||
};
|
||||
return (
|
||||
<div className="bg-hand" role="group" aria-label={label} onKeyDown={onKey}>
|
||||
<div className="bg-hand" data-fx={fx} role="group" aria-label={label} onKeyDown={onKey}>
|
||||
{hand.map((c) => {
|
||||
const ok = okOf?.(c);
|
||||
return (
|
||||
@@ -595,7 +676,7 @@ function MyArea({
|
||||
|
||||
return (
|
||||
<section className="bg-me" aria-label="내 자리">
|
||||
<div className="bg-mehead">
|
||||
<div className="bg-mehead" data-fx="bang-me">
|
||||
<RoleCard role={my.role} hints={hints} always={!!v.winner || !meP?.alive} />
|
||||
<span className="stack" style={{ gap: 2, flex: '1 1 220px', minWidth: 0 }}>
|
||||
<strong>
|
||||
@@ -619,6 +700,7 @@ function MyArea({
|
||||
{prompt?.kind === 'draw' && <DrawPanel prompt={prompt} act={act} pending={pending} players={players} />}
|
||||
{meP?.alive && (
|
||||
<HandCards
|
||||
fx="bang-hand"
|
||||
hand={my.hand}
|
||||
label={`내 카드 ${my.hand.length}장. 좌우 방향키로 고르고 Enter로 눌러요`}
|
||||
okOf={(c) => (discarding || sidMode ? undefined : playing ? !!optOf(c.id)?.ok : undefined)}
|
||||
@@ -974,6 +1056,8 @@ function BangBoard({ view: v, me, players, act, pending }: BoardProps<BangView>)
|
||||
useEffect(() => {
|
||||
if (last && !mine) setAnnounce(logText(last, players));
|
||||
}, [last?.seq, last?.t]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const [banner, showBanner] = useBanner();
|
||||
useBangFx(v, me, players, showBanner);
|
||||
|
||||
const n = v.players.length;
|
||||
const myIdx = v.players.findIndex((p) => p.id === me);
|
||||
@@ -1018,10 +1102,313 @@ function BangBoard({ view: v, me, players, act, pending }: BoardProps<BangView>)
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{banner}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const TEAM_TONE: Record<Team, BannerTone> = { law: 'blue', outlaws: 'red', renegade: 'gold' };
|
||||
|
||||
/**
|
||||
* Sounds + motion for every change of the table, mine or anyone else's: the log entries that are new since the last
|
||||
* view (never on the first render, so joining / reloading / a replay jump stays quiet).
|
||||
*/
|
||||
function useBangFx(v: BangView, me: string | null, players: Record<string, PublicUser>, showBanner: (text: string, tone?: BannerTone, sub?: string) => void) {
|
||||
// Entries of one action share `seq`; count repeats (two 판정 cards, Black Jack's two draws) so every key is unique.
|
||||
const keyed = useMemo(() => {
|
||||
const seen = new Map<string, number>();
|
||||
return v.log.map((e) => {
|
||||
const base = `${e.seq}-${e.t}-${'p' in e ? e.p : ''}`;
|
||||
const i = seen.get(base) ?? 0;
|
||||
seen.set(base, i + 1);
|
||||
return { e, k: `${base}-${i}` };
|
||||
});
|
||||
}, [v.log]);
|
||||
/** Last known place of my hand cards: a card I played is gone from the DOM once the view arrives. */
|
||||
const handRects = useRef(new Map<string, { r: DOMRect; f: CardFace }>());
|
||||
/** Where my next new hand cards come from (deck by default) and when. */
|
||||
const handSrc = useRef<{ from: Element | DOMRect | null; at: number } | null>(null);
|
||||
|
||||
const visible = (el: Element | null) => (el && el.getBoundingClientRect().width > 0 ? el : null);
|
||||
/** A player's seat; my own seat is hidden on phones, so my area stands in for it. */
|
||||
const place = (id: string): Element | null => visible(seatEl(id)) ?? (id === me ? fxEl('bang-me') : null);
|
||||
/** Where a card I (or someone) just used came from. */
|
||||
const srcOf = (id: string, f?: CardFace): Element | DOMRect | null => {
|
||||
if (id === me && f) {
|
||||
const hand = new Set(v.my?.hand.map((c) => c.id) ?? []);
|
||||
for (const [cid, x] of handRects.current) {
|
||||
if (hand.has(cid) || !sameFace(x.f, f)) continue;
|
||||
handRects.current.delete(cid);
|
||||
return x.r;
|
||||
}
|
||||
}
|
||||
return place(id);
|
||||
};
|
||||
const name = (id: string) => `${nick(players, id)}님`;
|
||||
|
||||
useNewEntries(
|
||||
keyed,
|
||||
(x) => x.k,
|
||||
(fresh) => {
|
||||
const deck = fxEl('bang-deck');
|
||||
const pile = fxEl('bang-discard') ?? deck;
|
||||
const piles = fxEl('bang-piles');
|
||||
const later = (ms: number, f: () => void) => (ms > 0 ? setTimeout(f, ms) : f());
|
||||
const toPile = (from: Element | DOMRect | null, f: CardFace | null, delay: number) => flyGhost(from, pile, { delay, ms: 420, ...(f ? faceGhost(f) : BACK_GHOST) });
|
||||
const toMe = (from: Element | null, at: number) => (handSrc.current = { from, at });
|
||||
const others = (p: string) => v.players.filter((x) => x.alive && x.id !== p).map((x) => x.id);
|
||||
let healed = false;
|
||||
let t = 0;
|
||||
for (const { e } of fresh) {
|
||||
const at = Math.min(t, 3000);
|
||||
switch (e.t) {
|
||||
case 'play': {
|
||||
const k = e.as ?? e.card.kind;
|
||||
toPile(srcOf(e.p, e.card), e.card, at);
|
||||
later(at, sfx.cardPlay);
|
||||
if (k === 'bang' && e.target) {
|
||||
const tg = e.target;
|
||||
flyGhost(place(e.p), place(tg), { kind: 'coin', label: '💥', className: 'bg-bullet', ms: 260, delay: at + 100 });
|
||||
bangSfx.shot(at + 100);
|
||||
later(at + 340, () => bump(place(tg), 'shake'));
|
||||
if (tg === me) later(at, () => showBanner('뱅!', 'red', `${name(e.p)}이 쐈어요`));
|
||||
t += 450;
|
||||
} else if (k === 'gatling') {
|
||||
bangSfx.gatling(at + 80);
|
||||
later(at, () => showBanner('개틀링!', 'red', name(e.p)));
|
||||
others(e.p).forEach((id, i) => later(at + 200 + i * 85, () => bump(place(id), 'shake')));
|
||||
t += 750;
|
||||
} else if (k === 'indians') {
|
||||
bangSfx.drums(at + 60);
|
||||
later(at, () => showBanner('인디언!', 'gold', name(e.p)));
|
||||
others(e.p).forEach((id, i) => later(at + 150 + i * 90, () => bump(place(id))));
|
||||
t += 650;
|
||||
} else if (k === 'duel') {
|
||||
bangSfx.duel(at + 80);
|
||||
if (e.target && (e.p === me || e.target === me)) later(at, () => showBanner('결투!', 'dark', `${name(e.p)} vs ${name(e.target!)}`));
|
||||
if (e.target) later(at + 120, () => bump(place(e.target!)));
|
||||
t += 650;
|
||||
} else if (k === 'generalStore') {
|
||||
later(at + 100, sfx.shuffle);
|
||||
t += 300;
|
||||
} else if (k === 'panic' || k === 'catBalou') {
|
||||
later(at + 100, sfx.whoosh);
|
||||
t += 250;
|
||||
} else t += 200;
|
||||
break;
|
||||
}
|
||||
case 'equip': {
|
||||
const to = e.target ?? e.p;
|
||||
flyGhost(srcOf(e.p, e.card), place(to), { delay: at, ms: 420, ...faceGhost(e.card) });
|
||||
later(at, sfx.cardPlay);
|
||||
if (e.card.kind === 'jail') {
|
||||
bangSfx.clank(at + 400);
|
||||
later(at + 400, () => bump(place(to), 'shake'));
|
||||
} else later(at + 400, () => bump(place(to)));
|
||||
if (e.replaced) toPile(place(to), e.replaced, at + 300);
|
||||
t += 400;
|
||||
break;
|
||||
}
|
||||
case 'check': {
|
||||
e.cards.forEach((c, i) => {
|
||||
flyGhost(deck, pile, { delay: at + i * 220, ms: 380, label: `${SUIT_SYMBOL[c.suit]}${c.rank}`, className: `bg-ghost chk${sr(c) === 'r' ? ' r' : ''}` });
|
||||
later(at + i * 220, sfx.cardFlip);
|
||||
});
|
||||
const end = at + 300 + (e.cards.length - 1) * 220;
|
||||
flip(fxEl('bang-check'), end);
|
||||
later(end + 80, e.success ? sfx.good : sfx.bad);
|
||||
t += 450 + (e.cards.length - 1) * 220;
|
||||
break;
|
||||
}
|
||||
case 'dynamite':
|
||||
if (e.exploded) {
|
||||
bangSfx.boom(at);
|
||||
later(at, () => {
|
||||
showBanner('펑!', 'dark', `${name(e.p)} 앞에서 다이너마이트가 터졌어요`);
|
||||
bump(place(e.p), 'shake');
|
||||
});
|
||||
t += 700;
|
||||
} else if (e.to) {
|
||||
flyGhost(place(e.p), place(e.to), { delay: at, ms: 420, label: '🧨', className: 'bg-ghost blue' });
|
||||
later(at, sfx.whoosh);
|
||||
t += 400;
|
||||
}
|
||||
break;
|
||||
case 'jail':
|
||||
flyGhost(place(e.p), pile, { delay: at + 200, ms: 400, label: '🔒', className: 'bg-ghost blue' });
|
||||
if (e.escaped) {
|
||||
later(at, () => {
|
||||
sfx.good();
|
||||
bump(place(e.p));
|
||||
});
|
||||
} else {
|
||||
bangSfx.clank(at);
|
||||
later(at, () => bump(place(e.p), 'shake'));
|
||||
if (e.p === me) later(at, () => showBanner('감옥!', 'dark', '이번 턴을 쉬어요'));
|
||||
}
|
||||
t += 450;
|
||||
break;
|
||||
case 'missed':
|
||||
e.cards.forEach((c, i) => toPile(srcOf(e.p, c), c, at + i * 80));
|
||||
bangSfx.ricochet(at);
|
||||
later(at, () => bump(place(e.p)));
|
||||
t += 350;
|
||||
break;
|
||||
case 'barrelSave':
|
||||
bangSfx.ricochet(at);
|
||||
later(at, () => bump(place(e.p)));
|
||||
t += 300;
|
||||
break;
|
||||
case 'respond':
|
||||
e.cards.forEach((c) => toPile(srcOf(e.p, c), c, at));
|
||||
if (e.why === 'duel') bangSfx.shot(at + 80);
|
||||
else later(at, sfx.cardPlay);
|
||||
t += 350;
|
||||
break;
|
||||
case 'hit':
|
||||
bangSfx.hit(at);
|
||||
later(at, () => {
|
||||
bump(place(e.p), 'shake');
|
||||
if (e.p === me) haptic([40, 40, 40]);
|
||||
});
|
||||
t += 350;
|
||||
break;
|
||||
case 'heal':
|
||||
e.cards?.forEach((c) => toPile(srcOf(e.p, c), c, at));
|
||||
if (!healed) bangSfx.beer(at);
|
||||
healed = healed || e.why === 'saloon';
|
||||
later(at + 200, () => bump(place(e.p)));
|
||||
t += e.why === 'saloon' ? 60 : 400;
|
||||
break;
|
||||
case 'draw': {
|
||||
const n = Math.min(e.n, 6);
|
||||
if (e.p === me) toMe(deck, at);
|
||||
else flyGhost(deck, place(e.p), { count: n, gap: 80, delay: at, ...BACK_GHOST });
|
||||
later(at, () => sfx.draw(Math.min(n, 4)));
|
||||
t += 120 + 80 * Math.min(n, 4);
|
||||
break;
|
||||
}
|
||||
case 'blackJack':
|
||||
later(at, sfx.cardFlip);
|
||||
if (e.extra) later(at + 150, () => {
|
||||
sfx.good();
|
||||
bump(place(e.p));
|
||||
});
|
||||
t += 250;
|
||||
break;
|
||||
case 'pedro':
|
||||
if (e.p === me) toMe(pile, at);
|
||||
else flyGhost(pile, place(e.p), { delay: at, ms: 420, ...faceGhost(e.card) });
|
||||
later(at, () => sfx.cardDeal());
|
||||
t += 250;
|
||||
break;
|
||||
case 'take':
|
||||
if (e.p === me) toMe(place(e.from), at);
|
||||
else flyGhost(place(e.from), place(e.p), { delay: at, ms: 420, ...(e.equip ? faceGhost(e.equip) : e.card ? faceGhost(e.card) : BACK_GHOST) });
|
||||
later(at, sfx.whoosh);
|
||||
t += 300;
|
||||
break;
|
||||
case 'discarded':
|
||||
toPile(place(e.p), e.card, at);
|
||||
later(at, () => {
|
||||
sfx.whoosh();
|
||||
bump(place(e.p), 'shake');
|
||||
});
|
||||
t += 300;
|
||||
break;
|
||||
case 'limit':
|
||||
e.cards.forEach((c, i) => toPile(srcOf(e.p, c), c, at + i * 70));
|
||||
later(at, () => sfx.deal(Math.min(e.cards.length, 4)));
|
||||
t += 250;
|
||||
break;
|
||||
case 'store':
|
||||
if (e.p === me) toMe(piles, at);
|
||||
else flyGhost(piles, place(e.p), { delay: at, ms: 420, ...faceGhost(e.card) });
|
||||
later(at, () => sfx.cardDeal());
|
||||
t += 250;
|
||||
break;
|
||||
case 'storeOpen':
|
||||
later(at, () => sfx.deal(Math.min(e.cards.length, 7)));
|
||||
later(at, () => bump(piles));
|
||||
t += 300;
|
||||
break;
|
||||
case 'dead': {
|
||||
const role = ROLE_INFO[e.role];
|
||||
bangSfx.death(at);
|
||||
later(at, () => {
|
||||
showBanner(e.left ? `${name(e.p)} 탈락` : `${name(e.p)} 쓰러짐`, 'dark', `${role.icon} ${role.name}였어요`);
|
||||
bump(place(e.p), 'shake');
|
||||
});
|
||||
flip(place(e.p)?.querySelector('.bg-role'), at + 200);
|
||||
t += 900;
|
||||
break;
|
||||
}
|
||||
case 'reward':
|
||||
later(at, sfx.collect);
|
||||
t += 150;
|
||||
break;
|
||||
case 'penalty':
|
||||
toPile(place(e.p), null, at);
|
||||
later(at, sfx.bad);
|
||||
t += 250;
|
||||
break;
|
||||
case 'vulture':
|
||||
if (e.p === me) toMe(place(e.from), at);
|
||||
else flyGhost(place(e.from), place(e.p), { count: Math.min(e.n, 6), gap: 70, delay: at, ...BACK_GHOST });
|
||||
later(at, sfx.collect);
|
||||
t += 350;
|
||||
break;
|
||||
case 'character':
|
||||
later(at, sfx.select);
|
||||
break;
|
||||
case 'turn':
|
||||
later(at, () => bump(place(e.p)));
|
||||
t += 100;
|
||||
break;
|
||||
case 'timeout':
|
||||
later(at, sfx.tick);
|
||||
break;
|
||||
case 'reshuffle':
|
||||
later(at, () => {
|
||||
sfx.shuffle();
|
||||
bump(deck, 'shake');
|
||||
});
|
||||
t += 300;
|
||||
break;
|
||||
case 'end':
|
||||
// The room already plays the win / lose sound.
|
||||
later(at + 300, () => showBanner(`${TEAM_KO[e.winner]} 승리!`, TEAM_TONE[e.winner]));
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
30,
|
||||
);
|
||||
|
||||
// New cards in my hand fly in from wherever they came from (deck, discard pile, another seat, the store).
|
||||
useNewEntries(
|
||||
v.my?.hand,
|
||||
(c) => c.id,
|
||||
(fresh) => {
|
||||
const src = handSrc.current ?? { from: fxEl('bang-deck'), at: 0 };
|
||||
fresh.forEach((c, i) =>
|
||||
flyFrom(document.querySelector(`[data-fx="bang-hand"] [data-id="${cssEsc(c.id)}"]`), src.from, { delay: Math.min(src.at, 3000) + i * 70, rotate: 8 }),
|
||||
);
|
||||
},
|
||||
20,
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
handSrc.current = null;
|
||||
const m = new Map<string, { r: DOMRect; f: CardFace }>();
|
||||
for (const c of v.my?.hand ?? []) {
|
||||
const el = document.querySelector(`[data-fx="bang-hand"] [data-id="${cssEsc(c.id)}"]`);
|
||||
if (el) m.set(c.id, { r: el.getBoundingClientRect(), f: c });
|
||||
}
|
||||
handRects.current = m;
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function BangSide({ view: v, me, players }: BoardProps<BangView>) {
|
||||
@@ -1034,7 +1421,7 @@ function BangSide({ view: v, me, players }: BoardProps<BangView>) {
|
||||
{v.winner ? ' · 게임 끝' : ''}
|
||||
</strong>
|
||||
<span className="small muted">
|
||||
카드 더미 {v.deckCount}장 · 버린 카드 {v.discardCount}장 · 반응 {v.options.reactionSeconds}초 · 턴 {v.options.turnSeconds}초
|
||||
카드 더미 {v.deckCount}장 · 버린 카드 {v.discardCount}장 · {secText('반응', v.options.reactionSeconds)} · {secText('턴', v.options.turnSeconds)}
|
||||
</span>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||
{v.players.map((p) => (
|
||||
@@ -1132,7 +1519,7 @@ function statusText(v: BangView, me: string | null, players: Record<string, Publ
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
return (
|
||||
<div className="segmented" role="group" aria-label={label}>
|
||||
{options.map(([k, l]) => (
|
||||
@@ -1168,10 +1555,10 @@ function Options({ value: o, onChange }: OptionsProps<BangOptions>) {
|
||||
<Seg label="캐릭터 정하기" value={o.characterDraft} options={[['random', '무작위 1장'], ['choose2', '2장 중 고르기']]} onChange={(characterDraft) => set({ characterDraft })} />
|
||||
</Field>
|
||||
<Field label="내 턴 제한 시간">
|
||||
<Seg label="내 턴 제한 시간" value={o.turnSeconds} options={[[30, '30초'], [60, '60초'], [90, '90초'], [120, '120초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||
<Seg label="내 턴 제한 시간" value={o.turnSeconds} options={[[30, '30초'], [60, '60초'], [90, '90초'], [120, '120초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||
</Field>
|
||||
<Field label="반응 제한 시간" help="빗나감!·맥주·결투·잡화점을 고르는 시간이에요.">
|
||||
<Seg label="반응 제한 시간" value={o.reactionSeconds} options={[[8, '8초'], [15, '15초'], [25, '25초']]} onChange={(reactionSeconds) => set({ reactionSeconds })} />
|
||||
<Field label="반응 제한 시간" help="빗나감!·맥주·결투·잡화점을 고르는 시간이에요. 무제한이어도 연결이 끊긴 채 오래 돌아오지 않으면 자동으로 골라요.">
|
||||
<Seg label="반응 제한 시간" value={o.reactionSeconds} options={[[8, '8초'], [15, '15초'], [25, '25초'], [null, '무제한']]} onChange={(reactionSeconds) => set({ reactionSeconds })} />
|
||||
</Field>
|
||||
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
|
||||
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
|
||||
@@ -1208,8 +1595,10 @@ function Options({ value: o, onChange }: OptionsProps<BangOptions>) {
|
||||
);
|
||||
}
|
||||
|
||||
const secText = (what: string, sec: number | null) => (sec === null ? `${what} 시간 무제한` : `${what} ${sec}초`);
|
||||
|
||||
function optionsSummary(o: BangOptions): string {
|
||||
const parts = [o.characterDraft === 'choose2' ? '캐릭터 고르기' : '캐릭터 무작위', `턴 ${o.turnSeconds}초`, `반응 ${o.reactionSeconds}초`];
|
||||
const parts = [o.characterDraft === 'choose2' ? '캐릭터 고르기' : '캐릭터 무작위', secText('턴', o.turnSeconds), secText('반응', o.reactionSeconds)];
|
||||
if (!o.autoDefend) parts.push('자동 방어 끔');
|
||||
if (o.drawBeforeDeath || o.beerAtFullHealth || o.selfTargetCatBalou || o.deputyCount7) parts.push('하우스 룰');
|
||||
return parts.join(' · ');
|
||||
@@ -1239,7 +1628,7 @@ function CardTable() {
|
||||
);
|
||||
}
|
||||
|
||||
function Rules() {
|
||||
function Rules({ options }: { options?: BangOptions }) {
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
@@ -1256,7 +1645,10 @@ function Rules() {
|
||||
<p>
|
||||
생명이 0이 되면 맥주로 살아날 수 있어요(2명 남으면 안 돼요). 무법자를 쓰러뜨리면 카드 3장을 받고, 보안관이 부관을 쓰러뜨리면 카드를 모두 버려요. 쓰러진 사람의 역할은 공개돼요.
|
||||
</p>
|
||||
<p className="small muted">반응 시간이 지나면 막을 카드가 있을 때 자동으로 내요(설정에서 끌 수 있어요). 내 역할은 역할 카드를 꾹 누르고 있을 때만 보여요.</p>
|
||||
<p className="small muted">
|
||||
{options?.reactionSeconds === null ? '이 방은 반응 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '반응 시간이 지나면'} 막을 카드가 있을 때 자동으로 내요(설정에서 끌 수
|
||||
있어요).{options?.turnSeconds === null ? ' 내 턴도 시간 제한이 없고, 연결이 끊긴 채 오래 돌아오지 않으면 턴을 자동으로 마쳐요.' : ''} 내 역할은 역할 카드를 꾹 누르고 있을 때만 보여요.
|
||||
</p>
|
||||
<CardTable />
|
||||
<table className="bg-rules small" style={{ borderCollapse: 'collapse', width: '100%' }}>
|
||||
<tbody>
|
||||
|
||||
62
apps/web/src/games/board-motion.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Shared movement for the two-player board games (오목·사목·오델로·체스·장기·바둑·쿼리도·윷놀이).
|
||||
* Everything reacts to the view changing, so the opponent's (and the computer's) moves get the same sound
|
||||
* and animation as mine. Animations are short and never take pointer events, so clicks are not slowed.
|
||||
* prefers-reduced-motion is handled by the global rule in styles/global.css.
|
||||
*/
|
||||
import { useRef, useState } from 'react';
|
||||
|
||||
/**
|
||||
* The snapshot from before the move counter last changed, and whether that change was a step forward.
|
||||
* `before` is null until the counter changes while the board is on screen, so a page load / reconnect shows
|
||||
* the position without replaying the last move. Computed during render (no extra frame without the piece).
|
||||
*/
|
||||
export function useMoveDiff<T>(snapshot: T, count: number): { before: T | null; forward: boolean } {
|
||||
const r = useRef<{ count: number; cur: T; before: T | null; forward: boolean }>({ count, cur: snapshot, before: null, forward: false });
|
||||
const s = r.current;
|
||||
if (count !== s.count) {
|
||||
s.before = s.cur;
|
||||
s.forward = count > s.count;
|
||||
s.count = count;
|
||||
}
|
||||
s.cur = snapshot;
|
||||
return { before: s.before, forward: s.forward };
|
||||
}
|
||||
|
||||
/**
|
||||
* For things shown only while they animate (captured / taken-back stones): `[over, end]`. Render them while
|
||||
* `over` is false and pass `end` to the last one's onAnimationEnd, so finished ghosts leave the DOM (and do not
|
||||
* count as pieces for tests or screen readers). A new `key` (move number) shows them again.
|
||||
*/
|
||||
export function useAnimOver(key: unknown): [boolean, () => void] {
|
||||
const [ended, setEnded] = useState<unknown>(undefined);
|
||||
return [ended === key, () => setEnded(key)];
|
||||
}
|
||||
|
||||
/**
|
||||
* SVG-friendly classes (scale around the element's own centre). Wrap the moving thing in its own `<g>` without a
|
||||
* `transform` attribute, because a CSS transform replaces the attribute while it runs.
|
||||
* - `bm-place`: a stone / piece set down (lands from a little above, slightly bigger, with a tiny settle).
|
||||
* - `bm-slide`: slides in from `--bm-dx/--bm-dy` (board units, e.g. `-2px` = two cells left) over `--bm-dur`.
|
||||
* - `bm-gone`: a captured piece shrinking and fading (key it by the move number; remove it with useAnimOver).
|
||||
* - `bm-ring`: one ripple ring around the last move.
|
||||
* - `bm-win`: winning line pulsing, staggered with `--bm-delay`.
|
||||
* - `bm-flash`: a quick bright flash (check / 장군).
|
||||
*/
|
||||
export const BOARD_MOTION_CSS = `
|
||||
.bm-place, .bm-gone, .bm-ring, .bm-win, .bm-flash { transform-box: fill-box; transform-origin: center; }
|
||||
.bm-place { animation: bm-place .26s cubic-bezier(.25, .9, .35, 1.25) both; pointer-events: none; }
|
||||
@keyframes bm-place { 0% { transform: translateY(-18%) scale(1.3); opacity: .15; } 70% { transform: translateY(0) scale(.97); opacity: 1; } 100% { transform: none; } }
|
||||
.bm-slide { animation: bm-slide var(--bm-dur, .24s) cubic-bezier(.3, .75, .35, 1) both; }
|
||||
@keyframes bm-slide { from { transform: translate(var(--bm-dx, 0px), var(--bm-dy, 0px)); } }
|
||||
.bm-gone { animation: bm-gone .42s ease-in forwards; pointer-events: none; }
|
||||
@keyframes bm-gone { 0% { opacity: 1; transform: scale(1); } 35% { opacity: .9; transform: scale(1.08); } 100% { opacity: 0; transform: scale(.35); } }
|
||||
.bm-ring { animation: bm-ring .55s ease-out .1s both; pointer-events: none; }
|
||||
@keyframes bm-ring { from { opacity: .85; transform: scale(.5); } to { opacity: 0; transform: scale(1.6); } }
|
||||
.bm-win { animation: bm-win 1.1s ease-in-out infinite; animation-delay: var(--bm-delay, 0ms); pointer-events: none; }
|
||||
@keyframes bm-win { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: .45; transform: scale(1.12); } }
|
||||
.bm-flash { animation: bm-flash .7s ease-out both; pointer-events: none; }
|
||||
@keyframes bm-flash { 0% { opacity: 0; } 20% { opacity: 1; } 100% { opacity: .55; } }
|
||||
/* The global reduced-motion rule makes animations 0.01ms long; an endless pulse would then flicker. */
|
||||
@media (prefers-reduced-motion: reduce) { .bm-win { animation: none; } }
|
||||
`;
|
||||
228
apps/web/src/games/card-fx.tsx
Normal file
@@ -0,0 +1,228 @@
|
||||
/**
|
||||
* Motion + sound helpers shared by the card games (포커·고스톱·달무티·99·도둑잡기·우노·바퀴벌레 포커·뱅!, 2026-10-13).
|
||||
*
|
||||
* - Everything reacts to *view changes*, so the other players' moves animate and sound too, and skips the first
|
||||
* render: joining, reloading or a replay jump (the replay page remounts the board) never replays old moves.
|
||||
* - Web Animations only (no layout change, `composite: 'add'` keeps the element's own transform), short (≤ 0.6 s),
|
||||
* and flying copies ("ghosts") never take clicks, so nothing waits for an animation.
|
||||
* - Respects `prefers-reduced-motion` (Web Animations are not covered by the global CSS rule, so it is checked here).
|
||||
* - Sounds stay in `lib/feedback` (`sfx`, `tone`, `noise`); game-specific ones live in each game folder.
|
||||
*/
|
||||
import { useLayoutEffect, useRef, useState, type ReactNode } from 'react';
|
||||
|
||||
export const reducedMotion = (): boolean => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
type Where = Element | DOMRect | null | undefined;
|
||||
|
||||
function rectOf(w: Where): DOMRect | null {
|
||||
if (!w) return null;
|
||||
const r = w instanceof Element ? w.getBoundingClientRect() : w;
|
||||
return r.width === 0 && r.height === 0 ? null : r;
|
||||
}
|
||||
|
||||
const center = (r: DOMRect) => ({ x: r.left + r.width / 2, y: r.top + r.height / 2 });
|
||||
|
||||
/** `CSS.escape` (games usually shadow `CSS` with their own style string). */
|
||||
export const cssEsc = (v: string): string => CSS.escape(v);
|
||||
|
||||
/** First element matching `[data-fx="<name>"]` (pile, deck, pot, hand …) or a seat `[data-fx-seat="<player id>"]`. */
|
||||
export const fxEl = (name: string): Element | null => document.querySelector(`[data-fx="${CSS.escape(name)}"]`);
|
||||
export const seatEl = (player: string): Element | null => document.querySelector(`[data-fx-seat="${CSS.escape(player)}"]`);
|
||||
|
||||
export interface FlyOpts {
|
||||
ms?: number;
|
||||
delay?: number;
|
||||
/** Start scale (default 0.6). */
|
||||
scale?: number;
|
||||
/** Start rotation in degrees (default -10). */
|
||||
rotate?: number;
|
||||
}
|
||||
|
||||
/** Makes `el` (already at its final place) fly in from `from` (an element or rect). */
|
||||
export function flyFrom(el: Element | null | undefined, from: Where, o: FlyOpts = {}): void {
|
||||
const a = rectOf(from);
|
||||
const b = rectOf(el);
|
||||
if (!el || !a || !b || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
|
||||
const p = center(a);
|
||||
const q = center(b);
|
||||
const dx = p.x - q.x;
|
||||
const dy = p.y - q.y;
|
||||
if (Math.abs(dx) + Math.abs(dy) < 4) return;
|
||||
(el as HTMLElement).animate(
|
||||
[
|
||||
{ transform: `translate(${dx}px, ${dy}px) scale(${o.scale ?? 0.6}) rotate(${o.rotate ?? -10}deg)`, opacity: 0.35 },
|
||||
{ transform: 'translate(0px, 0px) scale(1) rotate(0deg)', opacity: 1 },
|
||||
],
|
||||
{ duration: o.ms ?? 380, delay: o.delay ?? 0, easing: 'cubic-bezier(.2,.8,.3,1)', fill: 'backwards', composite: 'add' },
|
||||
);
|
||||
}
|
||||
|
||||
export type GhostKind = 'card' | 'hwatu' | 'chip' | 'coin';
|
||||
|
||||
export interface GhostOpts {
|
||||
kind?: GhostKind;
|
||||
/** How many copies (staggered by `gap` ms), e.g. dealing 3 cards or a stack of chips. */
|
||||
count?: number;
|
||||
gap?: number;
|
||||
ms?: number;
|
||||
delay?: number;
|
||||
/** Optional text on the ghost (a chip amount, a card name). */
|
||||
label?: string;
|
||||
/** Extra class for a game-specific look (game CSS must target `.fx-ghost.<class>`). */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const GHOST_SIZE: Record<GhostKind, [number, number]> = { card: [40, 56], hwatu: [34, 54], chip: [22, 22], coin: [22, 22] };
|
||||
|
||||
/**
|
||||
* A temporary copy flying from one place to another (card dealt to a seat, chips to the pot, pot to the winner …).
|
||||
* Fixed-position, pointer-events none, removed when done.
|
||||
*/
|
||||
export function flyGhost(from: Where, to: Where, o: GhostOpts = {}): void {
|
||||
const a = rectOf(from);
|
||||
const b = rectOf(to);
|
||||
if (!a || !b || reducedMotion() || typeof document === 'undefined') return;
|
||||
ensureCss();
|
||||
const kind = o.kind ?? 'card';
|
||||
const [w, h] = GHOST_SIZE[kind];
|
||||
const p = center(a);
|
||||
const q = center(b);
|
||||
const n = Math.max(1, Math.min(o.count ?? 1, 12));
|
||||
for (let i = 0; i < n; i++) {
|
||||
const g = document.createElement('div');
|
||||
g.className = `fx-ghost fx-ghost-${kind}${o.className ? ` ${o.className}` : ''}`;
|
||||
g.setAttribute('aria-hidden', 'true');
|
||||
if (o.label) g.textContent = o.label;
|
||||
g.style.left = `${p.x - w / 2}px`;
|
||||
g.style.top = `${p.y - h / 2}px`;
|
||||
document.body.appendChild(g);
|
||||
const jitter = n > 1 ? (i - (n - 1) / 2) * 6 : 0;
|
||||
const anim = g.animate(
|
||||
[
|
||||
{ transform: 'translate(0px, 0px) scale(.85) rotate(-8deg)', opacity: 0 },
|
||||
{ opacity: 1, offset: 0.15 },
|
||||
{ transform: `translate(${q.x - p.x + jitter}px, ${q.y - p.y}px) scale(1) rotate(0deg)`, opacity: 1, offset: 0.85 },
|
||||
{ transform: `translate(${q.x - p.x + jitter}px, ${q.y - p.y}px) scale(.9) rotate(0deg)`, opacity: 0 },
|
||||
],
|
||||
{ duration: o.ms ?? 480, delay: (o.delay ?? 0) + i * (o.gap ?? 70), easing: 'cubic-bezier(.3,.7,.3,1)', fill: 'both' },
|
||||
);
|
||||
const done = () => g.remove();
|
||||
anim.onfinish = done;
|
||||
anim.oncancel = done;
|
||||
// Safety net (a background tab may never finish the animation).
|
||||
setTimeout(done, (o.ms ?? 480) + (o.delay ?? 0) + i * (o.gap ?? 70) + 1500);
|
||||
}
|
||||
}
|
||||
|
||||
/** Quick attention wiggle / pop on an element that is already there (a seat that drew, a counter that changed). */
|
||||
export function bump(el: Element | null | undefined, kind: 'pop' | 'shake' = 'pop'): void {
|
||||
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
|
||||
const frames =
|
||||
kind === 'pop'
|
||||
? [{ transform: 'scale(1)' }, { transform: 'scale(1.12)', offset: 0.4 }, { transform: 'scale(1)' }]
|
||||
: [
|
||||
{ transform: 'translateX(0px)' },
|
||||
{ transform: 'translateX(-6px) rotate(-2deg)', offset: 0.25 },
|
||||
{ transform: 'translateX(6px) rotate(2deg)', offset: 0.5 },
|
||||
{ transform: 'translateX(-4px) rotate(-1deg)', offset: 0.75 },
|
||||
{ transform: 'translateX(0px)' },
|
||||
];
|
||||
(el as HTMLElement).animate(frames, { duration: kind === 'pop' ? 320 : 420, easing: 'ease-out', composite: 'add' });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- hooks
|
||||
|
||||
/**
|
||||
* Calls `onNew` (in a layout effect, before paint, so new elements can still be animated from elsewhere) with the
|
||||
* entries of `list` whose `key` was not there on the previous render. Never on the first render. A jump of more
|
||||
* than `max` new entries at once (resync, reconnect) is skipped silently.
|
||||
*/
|
||||
export function useNewEntries<T>(list: readonly T[] | null | undefined, key: (t: T) => string | number, onNew: (fresh: T[]) => void, max = 12): void {
|
||||
const seen = useRef<Set<string | number> | null>(null);
|
||||
const cb = useRef(onNew);
|
||||
cb.current = onNew;
|
||||
useLayoutEffect(() => {
|
||||
const items = list ?? [];
|
||||
const keys = items.map(key);
|
||||
const prev = seen.current;
|
||||
seen.current = new Set(keys);
|
||||
if (!prev) return;
|
||||
const fresh = items.filter((_, i) => !prev.has(keys[i]!));
|
||||
if (fresh.length && fresh.length <= max) cb.current(fresh);
|
||||
});
|
||||
}
|
||||
|
||||
/** Calls `onChange(now, before)` in a layout effect when `value` (compared with `Object.is`) changes; not on the first render. */
|
||||
export function useChange<T>(value: T, onChange: (now: T, before: T) => void): void {
|
||||
const prev = useRef<{ v: T } | null>(null);
|
||||
const cb = useRef(onChange);
|
||||
cb.current = onChange;
|
||||
useLayoutEffect(() => {
|
||||
const before = prev.current;
|
||||
prev.current = { v: value };
|
||||
if (before && !Object.is(before.v, value)) cb.current(value, before.v);
|
||||
}, [value]);
|
||||
}
|
||||
|
||||
export type BannerTone = 'gold' | 'red' | 'blue' | 'green' | 'dark';
|
||||
|
||||
/**
|
||||
* Big short banner over the screen (우노!, 뻑!, 고!, 혁명!, 뱅! …). `show` replaces the current one.
|
||||
* Render `node` once inside the board.
|
||||
*/
|
||||
export function useBanner(): [ReactNode, (text: string, tone?: BannerTone, sub?: string) => void] {
|
||||
const [b, setB] = useState<{ id: number; text: string; tone: BannerTone; sub?: string } | null>(null);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const show = (text: string, tone: BannerTone = 'gold', sub?: string) => {
|
||||
ensureCss();
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
setB((old) => ({ id: (old?.id ?? 0) + 1, text, tone, sub }));
|
||||
timer.current = setTimeout(() => setB(null), 1700);
|
||||
};
|
||||
useLayoutEffect(() => () => {
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
}, []);
|
||||
const node = b ? (
|
||||
<div className="fx-banner-wrap" aria-hidden>
|
||||
<div key={b.id} className={`fx-banner anim-banner fx-${b.tone}`}>
|
||||
{b.text}
|
||||
{b.sub && <small>{b.sub}</small>}
|
||||
</div>
|
||||
</div>
|
||||
) : null;
|
||||
return [node, show];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- CSS
|
||||
|
||||
const FX_CSS = `
|
||||
.fx-ghost { position: fixed; z-index: 60; pointer-events: none; box-sizing: border-box; will-change: transform, opacity; }
|
||||
.fx-ghost-card { width: 40px; height: 56px; border-radius: 6px; background: #1e3a8a; border: 2px solid #fff;
|
||||
box-shadow: 0 3px 8px rgba(0,0,0,.35), inset 0 0 0 4px #1e3a8a, inset 0 0 0 6px #93c5fd; }
|
||||
.fx-ghost-hwatu { width: 34px; height: 54px; border-radius: 4px; background: #b91c1c; border: 2px solid #1f2937;
|
||||
box-shadow: 0 3px 8px rgba(0,0,0,.35), inset 0 0 0 3px #7f1d1d; }
|
||||
.fx-ghost-chip, .fx-ghost-coin { width: 22px; height: 22px; border-radius: 50%; display: flex; align-items: center; justify-content: center;
|
||||
font: 800 10px/1 system-ui, sans-serif; color: #fff; white-space: nowrap; }
|
||||
.fx-ghost-chip { background: #dc2626; border: 3px dashed #fff; box-shadow: 0 2px 5px rgba(0,0,0,.4), 0 0 0 1px #7f1d1d; }
|
||||
.fx-ghost-coin { background: #f59e0b; border: 2px solid #fde68a; box-shadow: 0 2px 5px rgba(0,0,0,.4), 0 0 0 1px #92400e; color: #451a03; }
|
||||
.fx-banner-wrap { position: fixed; inset: 0; z-index: 70; display: flex; align-items: center; justify-content: center; pointer-events: none; }
|
||||
.fx-banner { pointer-events: none; font-size: clamp(2.2rem, 9vw, 4.6rem); font-weight: 900; letter-spacing: .02em; line-height: 1.05; text-align: center;
|
||||
padding: .18em .6em; border-radius: 22px; color: #fff; border: 5px solid #fff; box-shadow: 0 10px 30px rgba(0,0,0,.4);
|
||||
text-shadow: 0 3px 0 rgba(0,0,0,.3); display: flex; flex-direction: column; align-items: center; max-width: 92vw; }
|
||||
.fx-banner small { font-size: .32em; font-weight: 800; text-shadow: none; opacity: .95; margin-top: .2em; }
|
||||
.fx-gold { background: linear-gradient(180deg, #f59e0b, #d97706); }
|
||||
.fx-red { background: linear-gradient(180deg, #ef4444, #b91c1c); }
|
||||
.fx-blue { background: linear-gradient(180deg, #3b82f6, #1d4ed8); }
|
||||
.fx-green { background: linear-gradient(180deg, #22c55e, #15803d); }
|
||||
.fx-dark { background: linear-gradient(180deg, #374151, #111827); }
|
||||
`;
|
||||
|
||||
let cssDone = false;
|
||||
function ensureCss(): void {
|
||||
if (cssDone || typeof document === 'undefined') return;
|
||||
cssDone = true;
|
||||
const s = document.createElement('style');
|
||||
s.dataset.fx = 'card-fx';
|
||||
s.textContent = FX_CSS;
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
@@ -57,3 +57,13 @@ test('그림 맞히기: 공개 / 끝', () => {
|
||||
s.final = { ranking: [], turns: [], summary: '호랑이님 우승!' };
|
||||
expect(helpNow(view(s, null), null, users)).toContain('호랑이님 우승!');
|
||||
});
|
||||
|
||||
test('그림 맞히기: 그리기 무제한이면 출제자에게 정답 공개 안내', async () => {
|
||||
const { setupGame, usersOf } = await import('../help-kit.test-util');
|
||||
const { GAMES } = await import('@bg/games');
|
||||
const users = usersOf(['A', 'B', 'C']);
|
||||
const { state } = setupGame('catchmind', 3, { drawSeconds: null, wordChoice: false });
|
||||
const d: string = state.turn.drawer;
|
||||
const t = helpNow(GAMES.catchmind!.view(state, d) as never, d, users);
|
||||
expect(t).toContain('[정답 공개하고 넘기기]');
|
||||
});
|
||||
|
||||
@@ -32,7 +32,7 @@ export function helpNow(v: CatchmindView, me: string | null, players: Record<str
|
||||
}
|
||||
const word = v.word ? `그릴 단어는 "${v.word}"예요(나와 맞힌 사람만 보여요). ` : '';
|
||||
const report = v.options.letterReport ? ' 글자를 쓰면 신고를 받아 0점이 될 수 있어요.' : '';
|
||||
return `${word}그림판에 손가락이나 마우스로 그려요. 아래 버튼으로 색, 굵기, 지우개(🧽), 되돌리기(↶), 전체 지우기(🗑)를 쓸 수 있어요.\n글자나 숫자는 쓰지 말고 그림으로만 설명해요.${report}\n그리는 동안 채팅은 못 하고 [거의 다 왔어요]·[비슷해요]·[아니에요] 반응 버튼만 보낼 수 있어요.`;
|
||||
return `${word}그림판에 손가락이나 마우스로 그려요. 아래 버튼으로 색, 굵기, 지우개(🧽), 되돌리기(↶), 전체 지우기(🗑)를 쓸 수 있어요.\n글자나 숫자는 쓰지 말고 그림으로만 설명해요.${report}\n그리는 동안 채팅은 못 하고 [거의 다 왔어요]·[비슷해요]·[아니에요] 반응 버튼만 보낼 수 있어요.${v.endsAt === null ? '\n그리기 시간은 무제한이에요. 아무도 못 맞히면 [정답 공개하고 넘기기]를 두 번 눌러 넘겨요.' : ''}`;
|
||||
}
|
||||
// guesser / solver
|
||||
if (v.phase === 'choosing') return `${turn} · ${drawer}이 그릴 단어를 고르고 있어요. 그림이 시작되면 보고 정답을 입력해요.${v.canChat ? ' 지금은 채팅만 할 수 있어요.' : ''}${away}`;
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
/** 그림 맞히기 화면 (docs/games/catchmind.md §5.5, §9). */
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react';
|
||||
import type { CanvasOp, CatchmindOptions, CatchmindView, ChatView, TurnEndReason } from '@bg/games/catchmind';
|
||||
import type { PublicUser, ServerMessage } from '@bg/shared/lite';
|
||||
import { nameHue } from '../../components/ChatMessage';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { useWide } from '../../lib/media';
|
||||
import { socket } from '../../net/socket';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
@@ -69,6 +70,23 @@ const CHAT_MAX = 100;
|
||||
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '나간 사람';
|
||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '나간 사람', avatar: null, kind: 'guest' };
|
||||
|
||||
/** Game sounds on top of the shared palette (site volume applies). */
|
||||
const cmSound = {
|
||||
/** Pencil touching the paper (drawer's own strokes only). */
|
||||
scribble: () => noise(50, 0.05, 0, 'highpass', 4500),
|
||||
/** A hint letter turned over. */
|
||||
hint: () => {
|
||||
tone(880, 70, 'triangle', 0.1);
|
||||
tone(1320, 110, 'triangle', 0.08, 60);
|
||||
},
|
||||
/** Somebody else got it. */
|
||||
otherCorrect: () => tone(1175, 120, 'triangle', 0.1),
|
||||
/** "아까워요!" (only the sender sees it). */
|
||||
close: () => tone(700, 90, 'triangle', 0.1, 0, { slideTo: 600 }),
|
||||
/** The drawer's reaction button (heard by the guessers). */
|
||||
react: () => tone(990, 60, 'sine', 0.08),
|
||||
};
|
||||
|
||||
const CSS = `
|
||||
.cm { width: 100%; max-width: 1100px; display: flex; flex-direction: column; gap: 8px; align-self: center; }
|
||||
.cm-top { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; justify-content: space-between; font-weight: 700; }
|
||||
@@ -126,7 +144,10 @@ const CSS = `
|
||||
.cm-chat-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 3px; overflow-y: auto; min-height: 120px; max-height: 260px; }
|
||||
.cm-side .cm-chat-list { max-height: 340px; }
|
||||
.cm-line { font-size: .95rem; line-height: 1.35; word-break: break-word; }
|
||||
.cm-line b { margin-right: 6px; }
|
||||
.cm-line b .cm-tag { margin: 0 0 0 6px; }
|
||||
.cm-line b { display: block; font-size: .8rem; font-weight: 800; color: hsl(var(--name-h, 212) 70% var(--chat-name-l)); }
|
||||
.cm-line:not(.sys):not(.react) { background: var(--surface-2); border-radius: 4px 12px 12px 12px; padding: 4px 10px; align-self: flex-start; max-width: 100%; }
|
||||
.cm-line.mine { background: var(--primary-soft); }
|
||||
.cm-line.sys { color: var(--success); font-weight: 800; }
|
||||
.cm-line.close { color: var(--warning); }
|
||||
.cm-line.blocked { color: var(--text-sub); font-style: italic; }
|
||||
@@ -135,6 +156,12 @@ const CSS = `
|
||||
.cm-form { display: flex; gap: 6px; }
|
||||
.cm-form .input { flex: 1; min-height: 48px; font-size: 1.05rem; }
|
||||
.cm-close { color: var(--warning); font-weight: 900; font-size: .95rem; animation: cm-shake .4s ease; }
|
||||
.cm-over { animation: fade .25s ease both; }
|
||||
.cm-over .word { animation: cm-word .5s cubic-bezier(.3,1.6,.5,1) both; animation-delay: .1s; }
|
||||
.cm-hint .ch.flip { animation: anim-flip .42s ease both; }
|
||||
.cm-strip .p .sc, .cm-score strong { display: inline-block; }
|
||||
.cm-unl { font-weight: 800; color: var(--text-sub); font-size: .92rem; }
|
||||
@keyframes cm-word { from { transform: scale(.3) rotate(-6deg); opacity: 0; } }
|
||||
.cm-away { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; background: var(--warning-soft); color: var(--text); border-radius: 12px; padding: 8px 12px; }
|
||||
@keyframes cm-pop { 0% { transform: translate(-50%, -50%) scale(.5); opacity: 0; } 70% { transform: translate(-50%, -50%) scale(1.08); opacity: 1; } 100% { transform: translate(-50%, -50%) scale(1); } }
|
||||
@keyframes cm-shake { 0%,100% { transform: none; } 25% { transform: translateX(-4px); } 75% { transform: translateX(4px); } }
|
||||
@@ -152,7 +179,7 @@ const CSS = `
|
||||
.cm-hint .ch { min-width: 34px; height: 40px; font-size: 1.35rem; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.cm-pop, .cm-close { animation: none; }
|
||||
.cm-pop, .cm-close, .cm-over, .cm-over .word, .cm-hint .ch.flip { animation: none; }
|
||||
.cm-bar i { transition: none; }
|
||||
}
|
||||
`;
|
||||
@@ -503,6 +530,7 @@ function Paper({ v, me, act, players }: { v: CatchmindView; me: string | null; a
|
||||
sender.begin(t.c, t.w, ex, x, y);
|
||||
drawing.apply({ k: 'b', s: sender.stroke, c: t.c, w: t.w, e: ex });
|
||||
drawing.addPoint(x, y);
|
||||
cmSound.scribble();
|
||||
};
|
||||
const onMove = (e: React.PointerEvent<HTMLCanvasElement>) => {
|
||||
if (active.current !== e.pointerId) return;
|
||||
@@ -602,6 +630,7 @@ function Paper({ v, me, act, players }: { v: CatchmindView; me: string | null; a
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{v.options.drawSeconds === null && <GiveUp act={act} />}
|
||||
{!wide && <span className="small muted">그리는 동안에는 채팅 대신 반응 버튼만 쓸 수 있어요.</span>}
|
||||
</div>
|
||||
)}
|
||||
@@ -609,6 +638,29 @@ function Paper({ v, me, act, players }: { v: CatchmindView; me: string | null; a
|
||||
);
|
||||
}
|
||||
|
||||
/** 무제한 drawings: the drawer may open the answer (press twice). */
|
||||
function GiveUp({ act }: { act: (a: unknown) => void }) {
|
||||
const [ask, setAsk] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!ask) return;
|
||||
const t = setTimeout(() => setAsk(false), 3000);
|
||||
return () => clearTimeout(t);
|
||||
}, [ask]);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`btn ${ask ? 'btn-primary' : 'btn-ghost'} btn-sm`}
|
||||
onClick={() => {
|
||||
if (!ask) return setAsk(true);
|
||||
setAsk(false);
|
||||
act({ type: 'giveUp' });
|
||||
}}
|
||||
>
|
||||
{ask ? '한 번 더 누르면 정답을 공개해요' : '🏳 정답 공개하고 넘기기'}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const END_TEXT: Record<TurnEndReason, string> = {
|
||||
time: '시간이 다 됐어요',
|
||||
allSolved: '모두 맞혔어요!',
|
||||
@@ -616,6 +668,7 @@ const END_TEXT: Record<TurnEndReason, string> = {
|
||||
report: '글자를 썼다는 신고로 끝났어요(출제자 0점)',
|
||||
drawerAway: '출제자의 연결이 끊겼어요',
|
||||
drawerLeft: '출제자가 나갔어요',
|
||||
giveUp: '출제자가 정답을 공개했어요',
|
||||
};
|
||||
|
||||
function Overlay({ v, me, act, players, onSave }: { v: CatchmindView; me: string | null; act: (a: unknown) => void; players: Record<string, PublicUser>; onSave: () => void }) {
|
||||
@@ -659,7 +712,12 @@ function OverlayMain({ v, act, players, onSave }: { v: CatchmindView; act: (a: u
|
||||
<h2>그릴 단어를 골라 주세요</h2>
|
||||
<div className="cm-choices">
|
||||
{v.choices.map((c, i) => (
|
||||
<button key={c.word} type="button" className="btn btn-primary" onClick={() => act({ type: 'chooseWord', index: i })} aria-label={`${c.word} (${CATEGORY_KO[c.category]})`}>
|
||||
<button
|
||||
key={c.word}
|
||||
type="button"
|
||||
className="btn btn-primary anim-deal"
|
||||
style={{ '--anim-delay': `${i * 90}ms` } as CSSProperties}
|
||||
onClick={() => act({ type: 'chooseWord', index: i })} aria-label={`${c.word} (${CATEGORY_KO[c.category]})`}>
|
||||
<span className="ic" aria-hidden>
|
||||
{CATEGORY_ICON[c.category]}
|
||||
</span>
|
||||
@@ -717,7 +775,7 @@ function HintRow({ v }: { v: CatchmindView }) {
|
||||
{hint ? (
|
||||
<span role="text" aria-label={`힌트: ${hint.filter((c) => c !== ' ').length}글자, ${hint.map((c) => (c === '○' ? '빈칸' : c === ' ' ? '띄어쓰기' : c)).join(' ')}`} style={{ display: 'inline-flex', gap: 6, flexWrap: 'wrap', justifyContent: 'center' }}>
|
||||
{hint.map((c, i) => (
|
||||
<span key={i} className={`ch${c === ' ' ? ' sp' : ''}${c !== '○' && c !== ' ' && !/^[ㄱ-ㅎ]$/.test(c) ? ' open' : ''}`} aria-hidden>
|
||||
<span key={`${i}-${c}`} className={`ch${c === ' ' ? ' sp' : ''}${c !== '○' && c !== ' ' && !/^[ㄱ-ㅎ]$/.test(c) ? ' open' : ''}${c !== '○' && c !== ' ' && v.phase === 'drawing' ? ' flip' : ''}`} aria-hidden>
|
||||
{c === ' ' ? '' : c}
|
||||
</span>
|
||||
))}
|
||||
@@ -732,7 +790,21 @@ function HintRow({ v }: { v: CatchmindView }) {
|
||||
|
||||
function TimeBar({ v }: { v: CatchmindView }) {
|
||||
const now = useServerNow(250);
|
||||
// Ticks in the last 10 seconds of the drawing.
|
||||
const lastSec = v.phase === 'drawing' && v.endsAt !== null ? Math.ceil(Math.max(0, v.endsAt - now) / 1000) : 0;
|
||||
const ticked = useRef(0);
|
||||
useEffect(() => {
|
||||
if (lastSec > 0 && lastSec <= 10 && lastSec !== ticked.current) sfx.tick();
|
||||
ticked.current = lastSec;
|
||||
}, [lastSec]);
|
||||
if (v.phase === 'ended') return null;
|
||||
if (v.endsAt === null || v.phaseMs === null) {
|
||||
return (
|
||||
<div className="cm-unl" role="status">
|
||||
⏱ 그리기 시간 무제한 · {v.options.guessMode === 'multi' ? '모두 맞히거나' : '누가 맞히거나'} 출제자가 정답을 공개할 때까지
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const left = Math.max(0, v.endsAt - now);
|
||||
const frac = Math.min(1, left / Math.max(1, v.phaseMs));
|
||||
const sec = Math.ceil(left / 1000);
|
||||
@@ -773,7 +845,7 @@ function ScoreStrip({ v, me, players }: { v: CatchmindView; me: string | null; p
|
||||
<span className="nm" aria-hidden style={{ fontWeight: id === me ? 900 : 700 }}>
|
||||
{nick(players, id)}
|
||||
</span>
|
||||
<span className="sc" aria-hidden>
|
||||
<span key={v.scores[id] ?? 0} className={`sc${v.scores[id] ? ' anim-bump' : ''}`} aria-hidden>
|
||||
{v.scores[id] ?? 0}점
|
||||
</span>
|
||||
</div>
|
||||
@@ -803,7 +875,7 @@ function ScoreList({ v, me, players }: { v: CatchmindView; me: string | null; pl
|
||||
✓ 맞힘
|
||||
</span>
|
||||
)}
|
||||
<strong style={{ fontVariantNumeric: 'tabular-nums' }} aria-hidden>
|
||||
<strong key={v.scores[id] ?? 0} className={v.scores[id] ? 'anim-bump' : undefined} style={{ fontVariantNumeric: 'tabular-nums' }} aria-hidden>
|
||||
{v.scores[id] ?? 0}점
|
||||
</strong>
|
||||
</li>
|
||||
@@ -847,8 +919,10 @@ function chatLine(m: ChatView, me: string | null, players: Record<string, Public
|
||||
cls: '',
|
||||
body: (
|
||||
<>
|
||||
{m.solversOnly && <span className="cm-tag">맞힌 사람끼리</span>}
|
||||
<b>{who}</b>
|
||||
<b>
|
||||
{who}
|
||||
{m.solversOnly && <span className="cm-tag">맞힌 사람끼리</span>}
|
||||
</b>
|
||||
{m.text}
|
||||
</>
|
||||
),
|
||||
@@ -911,7 +985,7 @@ function GuessPanel({ v, me, players, act, pending }: { v: CatchmindView; me: st
|
||||
{v.chat.map((m) => {
|
||||
const { cls, body } = chatLine(m, me, players, v.drawer);
|
||||
return (
|
||||
<li key={m.id} className={`cm-line ${cls}`}>
|
||||
<li key={m.id} className={`cm-line ${cls}${m.from === me ? ' mine' : ''} anim-slide-up`} style={{ '--name-h': nameHue(m.from) } as CSSProperties}>
|
||||
{body}
|
||||
</li>
|
||||
);
|
||||
@@ -977,8 +1051,40 @@ function AwayBanner({ v, me, act }: { v: CatchmindView; me: string | null; act:
|
||||
);
|
||||
}
|
||||
|
||||
/** Sounds for what happens on the table (my own "정답!" is played by the overlay). */
|
||||
function useTableSounds(v: CatchmindView, me: string | null): void {
|
||||
const prev = useRef(v);
|
||||
useEffect(() => {
|
||||
const p = prev.current;
|
||||
prev.current = v;
|
||||
if (p === v) return;
|
||||
const turnChanged = p.turnNo !== v.turnNo;
|
||||
if (turnChanged && v.phase === 'choosing') {
|
||||
if (v.drawer === me) {
|
||||
sounds.myTurn();
|
||||
sfx.deal(v.choices?.length ?? 1);
|
||||
} else sfx.whoosh();
|
||||
}
|
||||
if (v.phase === 'drawing' && (p.phase !== 'drawing' || turnChanged)) sfx.whoosh();
|
||||
if (!turnChanged && v.phase === 'drawing' && v.hintStage > p.hintStage) cmSound.hint();
|
||||
// New chat lines: someone else got it, the drawer reacted, my "아까워요".
|
||||
const seen = p.chat.at(-1)?.id ?? 0;
|
||||
const fresh = v.chat.filter((m) => m.id > seen);
|
||||
if (fresh.some((m) => m.kind === 'correct' && m.from !== me)) cmSound.otherCorrect();
|
||||
if (v.role !== 'drawer' && fresh.some((m) => m.kind === 'reaction')) cmSound.react();
|
||||
if (fresh.some((m) => m.kind === 'close' && m.from === me)) cmSound.close();
|
||||
if (!turnChanged && p.phase === 'drawing' && v.phase === 'reveal') {
|
||||
if (v.endReason === 'report') sfx.alarm();
|
||||
else if (v.endReason === 'allSolved') sfx.fanfare();
|
||||
else if (v.solvers.length === 0) sfx.bad();
|
||||
else sfx.cardFlip();
|
||||
}
|
||||
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}
|
||||
|
||||
function CatchmindBoard({ view: v, me, players, act, pending }: BoardProps<CatchmindView>) {
|
||||
const wide = useWide();
|
||||
useTableSounds(v, me);
|
||||
return (
|
||||
<div className="cm">
|
||||
<style>{CSS}</style>
|
||||
@@ -1062,7 +1168,7 @@ function statusText(v: CatchmindView, me: string | null, players: Record<string,
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
return (
|
||||
<div className="segmented" role="group" aria-label={label}>
|
||||
{options.map(([k, l]) => (
|
||||
@@ -1131,9 +1237,11 @@ function Options({ value: o, onChange }: OptionsProps<CatchmindOptions>) {
|
||||
[80, '80초'],
|
||||
[100, '100초'],
|
||||
[120, '120초'],
|
||||
[null, '무제한'],
|
||||
]}
|
||||
onChange={(drawSeconds) => set({ drawSeconds })}
|
||||
/>
|
||||
{o.drawSeconds === null && <span className="small muted">맞힐 때까지 그려요. 아무도 못 맞히면 출제자가 [정답 공개하고 넘기기]로 넘겨요. 힌트는 80초 기준으로 나와요.</span>}
|
||||
</Field>
|
||||
<Field label="단어 난이도">
|
||||
<Seg
|
||||
@@ -1206,7 +1314,7 @@ function Options({ value: o, onChange }: OptionsProps<CatchmindOptions>) {
|
||||
function optionsSummary(o: CatchmindOptions): string {
|
||||
const hint = o.hints === 'full' ? '힌트 많이' : o.hints === 'basic' ? '글자 수 힌트' : '힌트 없음';
|
||||
const diff = o.difficulty === 'easy' ? '쉬운 단어' : o.difficulty === 'normal' ? '보통 단어' : '';
|
||||
return [o.guessMode === 'multi' ? '여러 명 맞히기' : '첫 정답자만', `${o.rounds}라운드`, `${o.drawSeconds}초`, hint, diff, o.customOnly ? '추가 단어만' : ''].filter(Boolean).join(' · ');
|
||||
return [o.guessMode === 'multi' ? '여러 명 맞히기' : '첫 정답자만', `${o.rounds}라운드`, o.drawSeconds === null ? '그리기 무제한' : `${o.drawSeconds}초`, hint, diff, o.customOnly ? '추가 단어만' : ''].filter(Boolean).join(' · ');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- rules
|
||||
@@ -1217,7 +1325,7 @@ function Rules({ options }: { options?: CatchmindOptions }) {
|
||||
<div className="stack">
|
||||
<p>
|
||||
한 사람(출제자)이 제시어를 <strong>그림으로</strong> 그리고, 나머지는 그림을 보며 <strong>채팅으로 정답</strong>을 맞혀요. 차례대로 돌아가며 모두 한 번씩 그리면 1라운드예요
|
||||
{o ? `(이 방은 ${o.rounds}라운드, 그리기 ${o.drawSeconds}초)` : ''}.
|
||||
{o ? `(이 방은 ${o.rounds}라운드, 그리기 ${o.drawSeconds === null ? '시간 무제한' : `${o.drawSeconds}초`})` : ''}.
|
||||
</p>
|
||||
<p>
|
||||
출제자는 단어 3개 중 하나를 10초 안에 골라요. 그리는 동안에는 글자를 쓰면 안 되고, 채팅 대신 "거의 다 왔어요" 같은 반응 버튼만 쓸 수 있어요. 글자를 쓰면 맞히는 사람들이 신고할 수 있어요.
|
||||
@@ -1228,7 +1336,10 @@ function Rules({ options }: { options?: CatchmindOptions }) {
|
||||
: '먼저 맞힐수록 점수가 커요: 10점, 8점, 6점, 그다음부터 4점. 출제자는 맞힌 사람 1명마다 2점(최대 12점)을 받아요.'}{' '}
|
||||
띄어쓰기·문장부호는 무시하고, "사과요"처럼 끝에 붙인 말도 정답으로 봐요. 거의 맞히면 나에게만 "아까워요!"가 떠요.
|
||||
</p>
|
||||
<p>시간이 지나면 힌트가 나와요: 처음엔 글자 수, 절반이 지나면 초성, 3/4이 지나면 한 글자. 점수가 같으면 많이 맞힌 사람이 앞서요.</p>
|
||||
<p>
|
||||
시간이 지나면 힌트가 나와요: 처음엔 글자 수, 절반이 지나면 초성, 3/4이 지나면 한 글자.{' '}
|
||||
{o?.drawSeconds === null ? '그리기 시간이 무제한이면 40초에 초성, 60초에 한 글자가 나오고, 아무도 못 맞히면 출제자가 정답을 공개하고 넘길 수 있어요. ' : ''}점수가 같으면 많이 맞힌 사람이 앞서요.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
67
apps/web/src/games/chess/fx.test.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import { expect, test } from 'bun:test';
|
||||
import { SeededRng } from '../../../../../packages/engine/src/rng';
|
||||
import { applyAction, setupGame } from '../help-kit.test-util';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { chessCues, chessMotion } from './fx';
|
||||
|
||||
const view = (s: unknown) => GAMES.chess!.view(s, null) as any;
|
||||
let clock = 1_700_000_000_000;
|
||||
const move = (s: any, who: string, from: string, to: string) => applyAction('chess', s, who, { type: 'move', from, to }, SeededRng.fromSeed([9, 9, 9, 9]), (clock += 1000));
|
||||
/** Plays [who, from, to] moves and returns the views before and after the last one. */
|
||||
function play(moves: [string, string, string][]) {
|
||||
let s = setupGame('chess', 2, { colorAssignment: 'hostWhite' }).state;
|
||||
let before = view(s);
|
||||
for (const [who, from, to] of moves) {
|
||||
before = view(s);
|
||||
s = move(s, who, from, to);
|
||||
}
|
||||
return { before, after: view(s) };
|
||||
}
|
||||
|
||||
test('체스 소리: 한 번의 변화에 한 묶음, 무르기는 휙', () => {
|
||||
expect(chessCues(3, [{ san: 'e4' }, { san: 'e5' }, { san: 'Nf3' }])).toEqual([]);
|
||||
expect(chessCues(0, [{ san: 'e4' }])).toEqual(['move']);
|
||||
expect(chessCues(0, [{ san: 'Bxf7+' }])).toEqual(['capture', 'check']);
|
||||
expect(chessCues(0, [{ san: 'O-O-O' }])).toEqual(['castle']);
|
||||
expect(chessCues(0, [{ san: 'exd8=Q#' }])).toEqual(['capture', 'promote', 'mate']);
|
||||
expect(chessCues(2, [{ san: 'e4' }])).toEqual(['undo']);
|
||||
});
|
||||
|
||||
test('체스 움직임: 보통 수는 한 기물만 미끄러지고, 잡힌 기물은 그 자리에서 사라짐', () => {
|
||||
const { before, after } = play([
|
||||
['A', 'e2', 'e4'],
|
||||
['B', 'd7', 'd5'],
|
||||
['A', 'e4', 'd5'],
|
||||
]);
|
||||
expect(chessMotion(before.board, after.board, after.lastMove)).toEqual({ slides: [{ sq: 'd5', from: 'e4' }], gone: [{ sq: 'd5', piece: 'p' }] });
|
||||
// Page load / undo: nothing to replay.
|
||||
expect(chessMotion(null, after.board, after.lastMove)).toBeNull();
|
||||
});
|
||||
|
||||
test('체스 움직임: 캐슬링은 룩도, 앙파상은 지나간 폰이 사라짐', () => {
|
||||
const castle = play([
|
||||
['A', 'e2', 'e4'],
|
||||
['B', 'e7', 'e5'],
|
||||
['A', 'g1', 'f3'],
|
||||
['B', 'b8', 'c6'],
|
||||
['A', 'f1', 'c4'],
|
||||
['B', 'f8', 'c5'],
|
||||
['A', 'e1', 'g1'],
|
||||
]);
|
||||
expect(castle.after.moves.at(-1).san).toBe('O-O');
|
||||
expect(chessMotion(castle.before.board, castle.after.board, castle.after.lastMove)).toEqual({
|
||||
slides: [
|
||||
{ sq: 'g1', from: 'e1' },
|
||||
{ sq: 'f1', from: 'h1' },
|
||||
],
|
||||
gone: [],
|
||||
});
|
||||
const ep = play([
|
||||
['A', 'e2', 'e4'],
|
||||
['B', 'a7', 'a6'],
|
||||
['A', 'e4', 'e5'],
|
||||
['B', 'd7', 'd5'],
|
||||
['A', 'e5', 'd6'],
|
||||
]);
|
||||
expect(chessMotion(ep.before.board, ep.after.board, ep.after.lastMove)).toEqual({ slides: [{ sq: 'd6', from: 'e5' }], gone: [{ sq: 'd5', piece: 'p' }] });
|
||||
});
|
||||
59
apps/web/src/games/chess/fx.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* What to play and animate when the chess view changes (pure, so it is unit-tested; no DOM or audio here).
|
||||
* Everything is derived from two consecutive views, so the opponent's and the computer's moves get the same
|
||||
* sound and motion as mine, and one change gives exactly one set of cues.
|
||||
*/
|
||||
|
||||
export type ChessCue = 'move' | 'capture' | 'castle' | 'promote' | 'check' | 'mate' | 'undo';
|
||||
|
||||
/** Sounds for a change of the move list from `prevCount` moves to `moves`. Empty when nothing changed. */
|
||||
export function chessCues(prevCount: number, moves: readonly { san: string }[]): ChessCue[] {
|
||||
const n = moves.length;
|
||||
if (n === prevCount) return [];
|
||||
if (n < prevCount) return ['undo'];
|
||||
const san = moves[n - 1]!.san;
|
||||
const out: ChessCue[] = [san.startsWith('O-O') ? 'castle' : san.includes('x') ? 'capture' : 'move'];
|
||||
if (san.includes('=')) out.push('promote');
|
||||
if (san.endsWith('#')) out.push('mate');
|
||||
else if (san.endsWith('+')) out.push('check');
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface ChessMotion {
|
||||
/** Pieces now on `sq` that slid in from `from` (the moved piece, plus the rook when castling). */
|
||||
slides: { sq: string; from: string }[];
|
||||
/** Captured pieces to fade out where they stood (the target square, or the passed pawn for en passant). */
|
||||
gone: { sq: string; piece: string }[];
|
||||
}
|
||||
|
||||
const FILES = 'abcdefgh';
|
||||
const idxOf = (sq: string) => (8 - Number(sq[1])) * 8 + FILES.indexOf(sq[0]!);
|
||||
const sqOfIdx = (i: number) => `${FILES[i % 8]}${8 - Math.floor(i / 8)}`;
|
||||
const isWhite = (p: string) => p === p.toUpperCase();
|
||||
|
||||
/**
|
||||
* Motion for one step forward: `before` is the board one move earlier (null on page load, after an undo or when
|
||||
* several moves arrived at once, so nothing is replayed then).
|
||||
*/
|
||||
export function chessMotion(before: readonly (string | null)[] | null, board: readonly (string | null)[], lastMove: { from: string; to: string } | null): ChessMotion | null {
|
||||
if (!before || !lastMove) return null;
|
||||
const moved = board[idxOf(lastMove.to)];
|
||||
if (!moved) return null;
|
||||
const white = isWhite(moved);
|
||||
const slides: ChessMotion['slides'] = [];
|
||||
// Chess960: the king may already stand on its castling square.
|
||||
if (lastMove.from !== lastMove.to) slides.push({ sq: lastMove.to, from: lastMove.from });
|
||||
const rook = white ? 'R' : 'r';
|
||||
const king = white ? 'K' : 'k';
|
||||
if (moved === king) {
|
||||
// Castling: one of my rooks left a square and one appeared elsewhere (Chess960 rooks may not move at all).
|
||||
const left = before.findIndex((p, i) => p === rook && board[i] !== rook);
|
||||
const came = board.findIndex((p, i) => p === rook && before[i] !== rook);
|
||||
if (left >= 0 && came >= 0) slides.push({ sq: sqOfIdx(came), from: sqOfIdx(left) });
|
||||
}
|
||||
const gone: ChessMotion['gone'] = [];
|
||||
before.forEach((p, i) => {
|
||||
if (p && isWhite(p) !== white && board[i] !== p) gone.push({ sq: sqOfIdx(i), piece: p });
|
||||
});
|
||||
return { slides, gone };
|
||||
}
|
||||
@@ -4,9 +4,12 @@ import type { ChessOptions, ChessView, LegalMove } from '@bg/games/chess';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
|
||||
import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { haptic } from '../../lib/feedback';
|
||||
import { BOARD_MOTION_CSS, useMoveDiff } from '../board-motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { chessCues, chessMotion } from './fx';
|
||||
import { helpNow } from './help';
|
||||
import { nopeSound, pickSound, playChess } from './sound';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
type Color = 'white' | 'black';
|
||||
@@ -133,6 +136,19 @@ function letterPiece(p: string): { type: PieceType; color: Color } {
|
||||
const LIGHT = '#efd9b4';
|
||||
const DARK = '#b38660';
|
||||
|
||||
/** Slide time for a piece moving `cells` squares (short hops quicker, long ones a little slower). */
|
||||
const slideSec = (cells: number) => Math.min(0.34, 0.2 + cells * 0.022);
|
||||
|
||||
/** Chess-only motion on top of BOARD_MOTION_CSS: the piece settling after it lands, check pulse, highlight fade-in. */
|
||||
const CHESS_CSS = `
|
||||
.ch-land { transform-box: fill-box; transform-origin: 50% 90%; animation: ch-land .2s ease-out both; animation-delay: var(--ch-delay, 0s); }
|
||||
@keyframes ch-land { 0% { transform: scale(1); } 40% { transform: scale(1.07, .95); } 100% { transform: scale(1); } }
|
||||
.ch-check { transform-box: fill-box; transform-origin: center; animation: ch-check .5s ease-out both; animation-delay: var(--ch-delay, 0s); }
|
||||
@keyframes ch-check { 0% { opacity: 0; transform: scale(.4); } 45% { opacity: 1; transform: scale(1.18); } 70% { transform: scale(.94); } 100% { opacity: 1; transform: scale(1); } }
|
||||
.ch-fade { animation: ch-fade .3s ease-out both; }
|
||||
@keyframes ch-fade { from { opacity: 0; } }
|
||||
`;
|
||||
|
||||
function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
|
||||
const myTurn = v.phase === 'playing' && v.myColor !== null && v.myColor === v.turn;
|
||||
const [flip, setFlip] = useState(false);
|
||||
@@ -147,8 +163,8 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const prevCount = useRef(v.moves.length);
|
||||
const movedRef = useRef<SVGGElement>(null);
|
||||
const dropped = useRef(false);
|
||||
/** Move number my drag-and-drop will create: that piece already sits where I let go, so it does not slide. */
|
||||
const dropped = useRef(-1);
|
||||
|
||||
const byFrom = useMemo(() => {
|
||||
const m = new Map<string, LegalMove[]>();
|
||||
@@ -158,43 +174,55 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
|
||||
const targets = selected ? (byFrom.get(selected) ?? []) : [];
|
||||
const showDots = v.hints !== 'off';
|
||||
|
||||
// What moved since the last change (mine, the opponent's or the computer's): slides, captured pieces, sounds.
|
||||
// Only a single step forward animates; a page load, an undo or several moves at once just show the position.
|
||||
const n = v.moves.length;
|
||||
const diff = useMoveDiff({ board: v.board, n }, n);
|
||||
const step = diff.forward && diff.before?.n === n - 1;
|
||||
const motion = step ? chessMotion(diff.before!.board, v.board, v.lastMove) : null;
|
||||
const myDrop = step && dropped.current === n;
|
||||
const slides = new Map<string, { dx: number; dy: number; sec: number }>();
|
||||
if (motion && !myDrop) {
|
||||
for (const sl of motion.slides) {
|
||||
const a = cellOf(sl.from, bottom);
|
||||
const b = cellOf(sl.sq, bottom);
|
||||
slides.set(sl.sq, { dx: a.x - b.x, dy: a.y - b.y, sec: slideSec(Math.hypot(a.x - b.x, a.y - b.y)) });
|
||||
}
|
||||
}
|
||||
/** When the moved piece lands (sounds and the settle wait for it). */
|
||||
const landSec = v.lastMove ? (slides.get(v.lastMove.to)?.sec ?? (slides.size ? Math.max(...[...slides.values()].map((x) => x.sec)) : 0)) : 0;
|
||||
|
||||
useEffect(() => {
|
||||
if (v.moves.length !== prevCount.current) {
|
||||
const last = v.moves[v.moves.length - 1];
|
||||
playChess(chessCues(prevCount.current, v.moves), landSec * 1000);
|
||||
if (v.moves.length > prevCount.current && last) {
|
||||
// Slide the moved piece in (~150ms) unless I just dropped it there myself.
|
||||
const el = movedRef.current;
|
||||
if (el && v.lastMove && !dropped.current && !matchMedia('(prefers-reduced-motion: reduce)').matches) {
|
||||
const a = cellOf(v.lastMove.from, bottom);
|
||||
const b = cellOf(v.lastMove.to, bottom);
|
||||
el.animate([{ transform: `translate(${a.x - b.x}px, ${a.y - b.y}px)` }, { transform: 'translate(0px, 0px)' }], { duration: 150, easing: 'ease-out' });
|
||||
}
|
||||
sounds.stone();
|
||||
setAnnounce(`${COLOR_KO[last.color]}: ${last.san}${v.checkSquare ? ', 체크!' : ''}`);
|
||||
if (myTurn) {
|
||||
haptic(40);
|
||||
if (document.visibilityState === 'hidden') sounds.myTurn();
|
||||
}
|
||||
if (myTurn) haptic(40);
|
||||
} else setAnnounce('수를 물렀어요.');
|
||||
}
|
||||
prevCount.current = v.moves.length;
|
||||
dropped.current = false;
|
||||
setSelected(null);
|
||||
setPromo(null);
|
||||
}, [v.moves.length]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const send = (from: string, to: string, promotion?: Promo) => {
|
||||
const send = (from: string, to: string, promotion?: Promo, viaDrop = false) => {
|
||||
dropped.current = viaDrop ? v.moves.length + 1 : -1;
|
||||
act({ type: 'move', from, to, ...(promotion ? { promotion } : {}) });
|
||||
setSelected(null);
|
||||
setPromo(null);
|
||||
setHover(null);
|
||||
};
|
||||
|
||||
const attempt = (from: string, to: string) => {
|
||||
const attempt = (from: string, to: string, viaDrop = false) => {
|
||||
const mv = (byFrom.get(from) ?? []).find((m) => m.to === to);
|
||||
if (!mv || pending) return;
|
||||
if (!mv || pending) {
|
||||
if (!mv && viaDrop) nopeSound();
|
||||
return;
|
||||
}
|
||||
// After the promotion sheet the piece is back on its square, so that move slides normally.
|
||||
if (mv.promotion && !v.autoQueen) setPromo({ from, to });
|
||||
else send(from, to);
|
||||
else send(from, to, undefined, viaDrop);
|
||||
};
|
||||
|
||||
const ownMovable = (sq: string) => myTurn && byFrom.has(sq);
|
||||
@@ -208,14 +236,17 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
|
||||
setSelected(null);
|
||||
setAnnounce(`${PIECE_KO[p.toLowerCase() as PieceType]}은 지금 움직일 수 없어요.`);
|
||||
haptic([30, 30, 30]);
|
||||
nopeSound();
|
||||
return;
|
||||
}
|
||||
if (!wasSelected && selected !== sq) pickSound();
|
||||
setSelected(wasSelected ? null : sq);
|
||||
return;
|
||||
}
|
||||
if (selected) {
|
||||
setAnnounce('그 칸으로는 갈 수 없어요.');
|
||||
haptic([30, 30, 30]);
|
||||
nopeSound();
|
||||
}
|
||||
setSelected(null);
|
||||
};
|
||||
@@ -260,6 +291,7 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
|
||||
|
||||
return (
|
||||
<div className="board-wrap stack" style={{ gap: 10 }}>
|
||||
<style>{BOARD_MOTION_CSS + CHESS_CSS}</style>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
viewBox="-0.02 -0.02 8.04 8.04"
|
||||
@@ -282,6 +314,7 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
|
||||
// Chess960: with the king picked, my own rook is a castling target, not a new selection.
|
||||
if (!sq || !ownMovable(sq) || pending || (selected && targets.some((m) => m.to === sq))) return;
|
||||
drag.current = { from: sq, wasSelected: selected === sq, sx: e.clientX, sy: e.clientY, moved: false };
|
||||
if (selected !== sq) pickSound();
|
||||
setSelected(sq);
|
||||
svgRef.current?.setPointerCapture(e.pointerId);
|
||||
}}
|
||||
@@ -300,10 +333,7 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
|
||||
drag.current = null;
|
||||
setDragPos(null);
|
||||
if (d?.moved) {
|
||||
if (sq && sq !== d.from) {
|
||||
dropped.current = true;
|
||||
attempt(d.from, sq);
|
||||
}
|
||||
if (sq && sq !== d.from) attempt(d.from, sq, true);
|
||||
return;
|
||||
}
|
||||
if (sq) click(sq, d ? d.wasSelected : false);
|
||||
@@ -325,14 +355,29 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
|
||||
const y = Math.floor(i / 8);
|
||||
return <rect key={i} x={x} y={y} width={1} height={1} fill={(x + y) % 2 === 0 ? LIGHT : DARK} />;
|
||||
})}
|
||||
{lastFrom && <rect x={lastFrom.x} y={lastFrom.y} width={1} height={1} fill="#cdd26a" opacity={0.75} />}
|
||||
{lastTo && <rect x={lastTo.x} y={lastTo.y} width={1} height={1} fill="#aaa23a" opacity={0.6} />}
|
||||
{lastFrom && lastTo && (
|
||||
<g key={`lm${n}`} className={step ? 'ch-fade' : undefined}>
|
||||
<rect x={lastFrom.x} y={lastFrom.y} width={1} height={1} fill="#cdd26a" opacity={0.75} />
|
||||
<rect x={lastTo.x} y={lastTo.y} width={1} height={1} fill="#aaa23a" opacity={0.6} />
|
||||
</g>
|
||||
)}
|
||||
{selected && <rect x={cell(selected).x} y={cell(selected).y} width={1} height={1} fill="#4f7a28" opacity={0.55} />}
|
||||
{v.threatened?.map((sq) => {
|
||||
const c = cell(sq);
|
||||
return <rect key={`t${sq}`} x={c.x + 0.04} y={c.y + 0.04} width={0.92} height={0.92} fill="none" stroke="#f59e0b" strokeWidth={0.07} strokeDasharray="0.14 0.08" />;
|
||||
})}
|
||||
{check && <rect x={check.x} y={check.y} width={1} height={1} fill="url(#chess-check)" />}
|
||||
{check && (
|
||||
<rect
|
||||
key={`ck${n}`}
|
||||
className={step ? 'ch-check' : undefined}
|
||||
style={{ '--ch-delay': `${landSec}s` } as React.CSSProperties}
|
||||
x={check.x}
|
||||
y={check.y}
|
||||
width={1}
|
||||
height={1}
|
||||
fill="url(#chess-check)"
|
||||
/>
|
||||
)}
|
||||
{/* Coordinates: files on the bottom row, ranks on the left column. */}
|
||||
{Array.from({ length: 8 }, (_, i) => (
|
||||
<g key={`c${i}`} fontSize={0.2} fontWeight={700} style={{ pointerEvents: 'none' }}>
|
||||
@@ -345,17 +390,38 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
|
||||
</g>
|
||||
))}
|
||||
{hoverTarget && <rect x={hoverTarget.x} y={hoverTarget.y} width={1} height={1} fill="#4f7a28" opacity={0.35} />}
|
||||
{/* Captured pieces (the en passant pawn too) shrink away where they stood, under the piece that took them. */}
|
||||
{motion?.gone.map((g) => {
|
||||
const c = cell(g.sq);
|
||||
return (
|
||||
<g key={`x${n}-${g.sq}`} transform={`translate(${c.x} ${c.y})`} style={{ pointerEvents: 'none' }}>
|
||||
<g className="bm-gone" style={{ animationDelay: `${Math.max(0, landSec - 0.12)}s` }}>
|
||||
<g transform="translate(0.04 0.04) scale(0.0092)">
|
||||
<PieceShape {...letterPiece(g.piece)} />
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{v.board.map((p, i) => {
|
||||
if (!p) return null;
|
||||
const sq = sqOf(i % 8, 7 - Math.floor(i / 8));
|
||||
if (sq === dragging) return null;
|
||||
const c = cell(sq);
|
||||
const { type, color } = letterPiece(p);
|
||||
const sl = slides.get(sq);
|
||||
// The moved piece (and the castling rook) is keyed by the move number so its animation runs once per move.
|
||||
const moved = step && (!!sl || v.lastMove?.to === sq);
|
||||
return (
|
||||
<g key={sq} transform={`translate(${c.x} ${c.y})`} style={{ pointerEvents: 'none' }}>
|
||||
<g ref={v.lastMove?.to === sq ? movedRef : undefined}>
|
||||
<g transform="translate(0.04 0.04) scale(0.0092)">
|
||||
<PieceShape type={type} color={color} />
|
||||
<g key={moved ? `${sq}-m${n}` : sq} transform={`translate(${c.x} ${c.y})`} style={{ pointerEvents: 'none' }}>
|
||||
<g
|
||||
className={sl ? 'bm-slide' : undefined}
|
||||
style={sl ? ({ '--bm-dx': `${sl.dx}px`, '--bm-dy': `${sl.dy}px`, '--bm-dur': `${sl.sec}s` } as React.CSSProperties) : undefined}
|
||||
>
|
||||
<g className={moved ? 'ch-land' : undefined} style={moved ? ({ '--ch-delay': `${sl?.sec ?? 0}s` } as React.CSSProperties) : undefined}>
|
||||
<g transform="translate(0.04 0.04) scale(0.0092)">
|
||||
<PieceShape type={type} color={color} />
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
@@ -385,10 +451,12 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
|
||||
})}
|
||||
{check && (
|
||||
<g transform={`translate(${check.x + 0.5} ${check.y < 1 ? check.y + 1.22 : check.y - 0.22})`} style={{ pointerEvents: 'none' }}>
|
||||
<rect x={-0.42} y={-0.17} width={0.84} height={0.34} rx={0.12} fill="#b91c1c" />
|
||||
<text textAnchor="middle" dominantBaseline="central" fontSize={0.2} fontWeight={800} fill="#fff">
|
||||
체크!
|
||||
</text>
|
||||
<g key={`cl${n}`} className={step ? 'anim-pop' : undefined} style={{ animationDelay: `${landSec + 0.08}s`, transformBox: 'fill-box', transformOrigin: 'center' }}>
|
||||
<rect x={-0.42} y={-0.17} width={0.84} height={0.34} rx={0.12} fill="#b91c1c" />
|
||||
<text textAnchor="middle" dominantBaseline="central" fontSize={0.2} fontWeight={800} fill="#fff">
|
||||
체크!
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
)}
|
||||
{dragging && dragPos && (
|
||||
|
||||
48
apps/web/src/games/chess/sound.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
/** Chess sounds: a light wooden "tok" family (site volume is applied inside feedback.ts). */
|
||||
import { noise, sfx, tone } from '../../lib/feedback';
|
||||
import type { ChessCue } from './fx';
|
||||
|
||||
/** A Staunton piece set down on a wooden board: short, soft and fairly high. */
|
||||
function tok(delay = 0, pitch = 1): void {
|
||||
tone(760 * pitch, 45, 'triangle', 0.15, delay, { slideTo: 520 * pitch });
|
||||
noise(30, 0.07, delay, 'bandpass', 2200 * pitch, 1.4);
|
||||
}
|
||||
|
||||
/** Each cue starts `d` ms from now (when the sliding piece lands). */
|
||||
const PLAY: Record<ChessCue, (d: number) => void> = {
|
||||
move: (d) => tok(d),
|
||||
// The moving piece, then the taken one knocked off the board.
|
||||
capture: (d) => {
|
||||
tok(d, 1.05);
|
||||
tone(420, 70, 'triangle', 0.11, d + 55, { slideTo: 300 });
|
||||
noise(60, 0.07, d + 55, 'lowpass', 1100);
|
||||
},
|
||||
// King and rook: two quick taps.
|
||||
castle: (d) => {
|
||||
tok(d, 1);
|
||||
tok(d + 110, 0.9);
|
||||
},
|
||||
// Like sfx.pop, a moment after the piece lands.
|
||||
promote: (d) => tone(700, 90, 'sine', 0.16, d + 90, { slideTo: 1400 }),
|
||||
// A short, light two-note call.
|
||||
check: (d) => {
|
||||
tone(988, 80, 'triangle', 0.09, d + 70);
|
||||
tone(1319, 130, 'triangle', 0.08, d + 150);
|
||||
},
|
||||
// The mating move: a low ringing chord (the win / lose jingle comes from the result screen).
|
||||
mate: (d) => {
|
||||
tone(392, 320, 'triangle', 0.11, d + 80);
|
||||
tone(587, 340, 'triangle', 0.08, d + 110);
|
||||
tone(784, 380, 'sine', 0.07, d + 140);
|
||||
},
|
||||
undo: () => sfx.whoosh(),
|
||||
};
|
||||
|
||||
export function playChess(cues: ChessCue[], delayMs = 0): void {
|
||||
for (const c of cues) PLAY[c](delayMs);
|
||||
}
|
||||
|
||||
/** Picking up one of my pieces: a very quiet tick. */
|
||||
export const pickSound = () => tone(1150, 25, 'triangle', 0.06);
|
||||
/** A tap that does nothing (wrong square / piece that cannot move): soft and low. */
|
||||
export const nopeSound = () => tone(230, 90, 'triangle', 0.06, 0, { slideTo: 180 });
|
||||
66
apps/web/src/games/clue/help.test.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { expect, test } from 'bun:test';
|
||||
import { applyAction, setupGame, usersOf } from '../help-kit.test-util';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { helpNow } from './help';
|
||||
|
||||
const ids = ['A', 'B', 'C'];
|
||||
const users = usersOf(ids);
|
||||
const view = (s: unknown, who: string | null) => GAMES.clue!.view(s, who) as any;
|
||||
const nickOf = (id: string) => users[id]!.nickname;
|
||||
|
||||
/** A fresh game with the current player standing in the library, ready to suggest. */
|
||||
function inLibrary() {
|
||||
const { state } = setupGame('clue', 3);
|
||||
const cur = state.current as string;
|
||||
const s = structuredClone(state);
|
||||
s.pos[s.suspectOf[cur]] = { at: 'library' };
|
||||
s.phase = { kind: 'suggest', room: 'library' };
|
||||
return { s, cur };
|
||||
}
|
||||
|
||||
test('클루: 주사위 차례 / 기다리기 / 관전', () => {
|
||||
const { state } = setupGame('clue', 3);
|
||||
const cur = state.current as string;
|
||||
const other = ids.find((p) => p !== cur)!;
|
||||
expect(helpNow(view(state, cur), cur, users)).toContain('[🎲 주사위 굴리기]');
|
||||
expect(helpNow(view(state, other), other, users)).toContain(`${nickOf(cur)}님이 이동하는 중이에요`);
|
||||
expect(helpNow(view(state, null), null, users)).toContain(`${nickOf(cur)}님 차례예요`);
|
||||
const rolled = applyAction('clue', state, cur, { type: 'roll' });
|
||||
expect(helpNow(view(rolled, cur), cur, users)).toContain('주사위 합은');
|
||||
});
|
||||
|
||||
test('클루: 추리 → 몰래 보여 주기 (보여 주는 사람 / 추리한 사람 / 다른 사람)', () => {
|
||||
const { s, cur } = inLibrary();
|
||||
expect(helpNow(view(s, cur), cur, users)).toContain('[추리하기]');
|
||||
// Ask about cards the next player surely holds: one of their own.
|
||||
const order = s.seats as string[];
|
||||
const next = order[(order.indexOf(cur) + 1) % 3]!;
|
||||
const third = order.find((p) => p !== cur && p !== next)!;
|
||||
const theirs: string[] = s.hands[next].map((c: string) => c.slice(5));
|
||||
const suspect = theirs.find((x) => ['scarlet', 'mustard', 'white', 'green', 'peacock', 'plum'].includes(x)) ?? 'plum';
|
||||
const weapon = theirs.find((x) => ['candlestick', 'dagger', 'pipe', 'revolver', 'rope', 'wrench'].includes(x)) ?? 'rope';
|
||||
const t = applyAction('clue', s, cur, { type: 'suggest', suspect, weapon });
|
||||
if (t.phase.kind === 'refute') {
|
||||
const r = t.phase.refuter as string;
|
||||
expect(helpNow(view(t, r), r, users)).toContain('한 장을 보여 줘야 해요');
|
||||
expect(helpNow(view(t, cur), cur, users)).toContain('나에게 보여 줄 카드를 고르는 중');
|
||||
const watcher = [next, third].find((p) => p !== r)!;
|
||||
expect(helpNow(view(t, watcher), watcher, users)).toContain('두 사람만 알아요');
|
||||
const done = applyAction('clue', t, r, { type: 'show', card: t.hands[r].find((c: string) => [suspect, weapon, 'library'].includes(c.slice(5))) });
|
||||
expect(helpNow(view(done, cur), cur, users)).toContain('보여 준 카드는 정답이 아니에요');
|
||||
} else {
|
||||
expect(helpNow(view(t, cur), cur, users)).toContain('아무도 카드를 보여 주지 못했어요');
|
||||
}
|
||||
});
|
||||
|
||||
test('클루: 고발이 틀려 탈락 / 게임 끝', () => {
|
||||
const { state } = setupGame('clue', 3);
|
||||
const cur = state.current as string;
|
||||
const sol = state.solution;
|
||||
const wrong = { type: 'accuse', suspect: sol.suspect === 'plum' ? 'green' : 'plum', weapon: sol.weapon, room: sol.room };
|
||||
const s = applyAction('clue', state, cur, wrong);
|
||||
expect(helpNow(view(s, cur), cur, users)).toContain('고발이 틀려서 탈락했어요');
|
||||
const next = s.current as string;
|
||||
const end = applyAction('clue', s, next, { type: 'accuse', ...sol });
|
||||
expect(helpNow(view(end, cur), cur, users)).toContain('게임이 끝났어요');
|
||||
});
|
||||
74
apps/web/src/games/clue/help.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
/** 클루 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { ClueView } from '@bg/games/clue';
|
||||
import { PASSAGES, ROOM_KO, SUSPECT_KO, WEAPON_KO, roomAt } from '@bg/games/clue/board';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
|
||||
const triple = (x: { suspect: keyof typeof SUSPECT_KO; weapon: keyof typeof WEAPON_KO; room: keyof typeof ROOM_KO }) =>
|
||||
`${SUSPECT_KO[x.suspect]} · ${WEAPON_KO[x.weapon]} · ${ROOM_KO[x.room]}`;
|
||||
|
||||
/** "서재로" / "식당으로" / "홀로": the particle after the last word. */
|
||||
const ro = (word: string) => {
|
||||
const c = word.charCodeAt(word.length - 1);
|
||||
const jong = c >= 0xac00 && c <= 0xd7a3 ? (c - 0xac00) % 28 : 0;
|
||||
return `${word}${jong === 0 || jong === 8 ? '로' : '으로'}`;
|
||||
};
|
||||
|
||||
export function helpNow(v: ClueView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const name = (id: string) => `${players[id]?.nickname ?? '다른 사람'}님`;
|
||||
const goal = '범인·흉기·장소 카드 한 장씩이 사건 봉투에 숨어 있어요. 추리로 남의 카드를 하나씩 알아내 봉투 속 정답을 맞히면 이겨요.';
|
||||
const ph = v.phase;
|
||||
if (ph.kind === 'finished') return `게임이 끝났어요. ${v.final?.summary ?? ''}`.trim() + '\n결과 창에서 [한 판 더]를 누르면 다시 할 수 있어요.';
|
||||
|
||||
const seated = !!me && v.seats.includes(me) && !v.left[me];
|
||||
const last = v.suggestions[v.suggestions.length - 1];
|
||||
const cur = name(v.current);
|
||||
|
||||
if (ph.kind === 'refute' && last) {
|
||||
if (ph.refuter === me)
|
||||
return `${name(last.by)}이 ${ro(triple(last))} 추리했어요. 그중 내 카드가 있어서 한 장을 보여 줘야 해요.\n파란 테두리 카드 중 하나를 누르면 ${name(last.by)}에게만 보여져요. 여러 장이면 원하는 카드를 골라요(이미 보여 준 카드를 또 보여 주면 새 정보를 덜 줘요).`;
|
||||
if (last.by === me) return `${name(ph.refuter)}이 나에게 보여 줄 카드를 고르는 중이에요. 보여 준 카드는 추리 노트에 자동으로 ✗ 표시돼요.`;
|
||||
return `${name(ph.refuter)}이 ${name(last.by)}에게 카드를 몰래 보여 주는 중이에요. 어떤 카드인지는 두 사람만 알아요.\n${name(ph.refuter)}이 ${triple(last)} 중 적어도 한 장은 가졌다는 것을 기억해 두세요.`;
|
||||
}
|
||||
|
||||
if (!seated) return `${cur} 차례예요. ${goal}`;
|
||||
if (v.out[me!])
|
||||
return `고발이 틀려서 탈락했어요. 더 움직이거나 추리할 수는 없지만, 다른 사람이 추리하면 가진 카드는 계속 보여 줘야 해요.\n지금은 ${cur} 차례예요.`;
|
||||
|
||||
if (v.current !== me) {
|
||||
const doing: Record<string, string> = {
|
||||
move: '이동하는 중이에요',
|
||||
moveTo: '갈 방을 고르는 중이에요',
|
||||
suggest: '추리할 범인과 흉기를 고르는 중이에요',
|
||||
afterSuggest: '고발할지 차례를 끝낼지 고르는 중이에요',
|
||||
};
|
||||
return `${cur}이 ${doing[ph.kind] ?? '차례를 진행하는 중이에요'}. 기다려 주세요.\n누가 무엇을 추리했고 누가 카드를 보여 주지 못했는지 기록을 보며 추리 노트를 정리해 보세요.`;
|
||||
}
|
||||
|
||||
const pos = v.pos[v.suspectOf[me!]!];
|
||||
const here = roomAt(pos);
|
||||
switch (ph.kind) {
|
||||
case 'move': {
|
||||
if (v.options.movement === 'free') return `내 차례예요. 지도에서 갈 방을 누르고 [들어가기]를 눌러요. 들어간 방에서 추리할 수 있어요.\n확신이 서면 [⚖️ 고발하기…]로 정답을 말해요. 틀리면 탈락이에요.`;
|
||||
const pass = here ? PASSAGES[here] : undefined;
|
||||
const extra = [
|
||||
pass ? `여기는 모서리 방이라 [🕳️ 비밀 통로]로 ${ROOM_KO[pass]}에 바로 갈 수도 있어요.` : '',
|
||||
here && v.movedIn[me!] ? `다른 사람의 추리로 ${ROOM_KO[here]}에 불려 왔으니 [여기서 추리하기]로 움직이지 않고 추리할 수도 있어요.` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
return `내 차례예요. [🎲 주사위 굴리기]를 눌러 나온 합만큼 복도를 걸어 방에 들어가요. ${extra}\n확신이 서면 [⚖️ 고발하기…]로 정답을 말해요. 틀리면 탈락이에요.`;
|
||||
}
|
||||
case 'moveTo': {
|
||||
const sum = v.dice ? v.dice[0] + v.dice[1] : 0;
|
||||
return `주사위 합은 ${sum}이에요. 지도에서 초록 방(${sum}칸 안)을 누르고 [들어가기]를 눌러요.\n점선 방을 고르면 그쪽으로 ${sum}칸 걸어가고 차례가 끝나요. 다음 차례에 이어서 가요.`;
|
||||
}
|
||||
case 'suggest':
|
||||
return `${ROOM_KO[ph.room]}에 들어왔어요. 범인과 흉기를 하나씩 고르고 [추리하기]를 눌러요. 장소는 지금 있는 ${ROOM_KO[ph.room]}이에요.\n다음 사람부터 차례로 셋 중 가진 카드 한 장을 나에게만 보여 줘요. ✗ 표시된 카드는 이미 정답이 아닌 카드예요.`;
|
||||
case 'afterSuggest':
|
||||
return last?.refuter
|
||||
? `${name(last.refuter)}이 보여 준 카드는 정답이 아니에요(노트에 자동 표시). [차례 끝내기]를 누르거나, 확신이 서면 [⚖️ 고발하기…]를 눌러요.`
|
||||
: '아무도 카드를 보여 주지 못했어요! 내 카드가 아니라면 셋 중에 정답이 있을 수 있어요. [차례 끝내기] 또는 [⚖️ 고발하기…]를 눌러요.';
|
||||
default:
|
||||
return `내 차례예요. ${goal}`;
|
||||
}
|
||||
}
|
||||
1088
apps/web/src/games/clue/index.tsx
Normal file
88
apps/web/src/games/clue/quick.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
/** 클루 30초 규칙 요약 (docs/07 §5). */
|
||||
import type { QuickCard } from '../types';
|
||||
|
||||
function Mini({ label, icon, hidden, tone }: { label: string; icon: string; hidden?: boolean; tone?: 'shown' | 'out' }) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
width: 62,
|
||||
height: 80,
|
||||
borderRadius: 9,
|
||||
border: `2px solid ${tone === 'shown' ? '#2563eb' : '#b79c6b'}`,
|
||||
background: hidden ? 'repeating-linear-gradient(45deg, #7c2d12 0 6px, #9a3412 6px 12px)' : 'linear-gradient(160deg, #fffaf0, #f1e6cf)',
|
||||
color: '#2b2118',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
fontWeight: 800,
|
||||
fontSize: 12,
|
||||
position: 'relative',
|
||||
boxShadow: tone === 'shown' ? '0 0 0 3px rgba(37,99,235,.35)' : '0 2px 0 rgba(0,0,0,.25)',
|
||||
}}
|
||||
>
|
||||
{hidden ? <span style={{ fontSize: 26, color: '#fff' }}>?</span> : <span style={{ fontSize: 24 }}>{icon}</span>}
|
||||
{!hidden && <span>{label}</span>}
|
||||
{tone === 'out' && <span style={{ position: 'absolute', top: -8, right: -6, color: '#dc2626', fontSize: 22, fontWeight: 900 }}>✗</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const row = { display: 'flex', gap: 8, alignItems: 'center', justifyContent: 'center' } as const;
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: (
|
||||
<div style={{ ...row, flexDirection: 'column' }}>
|
||||
<span style={{ fontSize: 34 }} aria-hidden>
|
||||
📁
|
||||
</span>
|
||||
<div style={row}>
|
||||
<Mini label="범인" icon="" hidden />
|
||||
<Mini label="흉기" icon="" hidden />
|
||||
<Mini label="장소" icon="" hidden />
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
alt: '사건 봉투 아래에 뒤집힌 카드 세 장(범인, 흉기, 장소)이 있어요',
|
||||
title: '봉투 속 세 장을 맞혀요',
|
||||
text: '범인·흉기·장소 카드가 한 장씩 사건 봉투에 숨어 있어요. 나머지 카드는 모두 나눠 가져요. 내 카드는 정답이 아니에요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<div style={row}>
|
||||
<div style={{ border: '2px solid #15803d', borderRadius: 10, padding: '8px 10px', background: '#dcfce7', color: '#14532d', fontWeight: 800, textAlign: 'center' }}>
|
||||
<div style={{ fontSize: 26 }}>🖋️</div>
|
||||
서재
|
||||
<div style={{ marginTop: 4 }}>
|
||||
<span style={{ display: 'inline-block', width: 22, height: 22, borderRadius: '50%', background: '#dc2626', color: '#fff', fontSize: 11, lineHeight: '22px' }}>스</span>
|
||||
</div>
|
||||
</div>
|
||||
<span style={{ fontSize: 30 }} aria-hidden>
|
||||
🎲
|
||||
</span>
|
||||
<span style={{ fontWeight: 800, fontSize: 15 }}>“플럼 교수가, 밧줄로, 서재에서!”</span>
|
||||
</div>
|
||||
),
|
||||
alt: '주사위를 굴려 서재에 들어간 빨간 말과 추리하는 말풍선이 있어요',
|
||||
title: '방에 들어가 추리해요',
|
||||
text: '주사위로 복도를 걸어 방에 들어가면, 그 방에서 "범인·흉기·이 방"을 말해 추리해요. 모서리 방은 비밀 통로로 건너가요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<div style={row}>
|
||||
<Mini label="밧줄" icon="🪢" tone="shown" />
|
||||
<span style={{ fontSize: 26 }} aria-hidden>
|
||||
➜
|
||||
</span>
|
||||
<Mini label="밧줄" icon="🪢" tone="out" />
|
||||
<span style={{ fontSize: 30 }} aria-hidden>
|
||||
⚖️
|
||||
</span>
|
||||
</div>
|
||||
),
|
||||
alt: '다른 사람이 몰래 보여 준 밧줄 카드에 노트에서 ✗ 표시를 하고, 저울(고발)이 있어요',
|
||||
title: '지우고, 고발해요',
|
||||
text: '다음 사람부터 셋 중 가진 카드 한 장을 나에게만 보여 줘요. 노트에서 지워 가다 확신이 서면 고발! 틀리면 탈락이에요.',
|
||||
},
|
||||
];
|
||||
@@ -4,7 +4,8 @@ import type { ClaimEntry, CockroachOptions, CockroachView, FrontView, Kind, Last
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { bump, flyGhost, seatEl, useBanner } from '../card-fx';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -213,6 +214,7 @@ const CSS = `
|
||||
.cp-seats { display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 10px; }
|
||||
.cp-seat { position: relative; background: var(--surface); border-radius: var(--radius-lg); padding: 9px 11px; box-shadow: var(--shadow); border: 3px solid transparent; display: flex; flex-direction: column; gap: 6px; min-width: 0; }
|
||||
.cp-seat.turn { border-color: var(--focus); }
|
||||
.fx-ghost.cp-ghost { background: linear-gradient(135deg, #7c2d12, #431407); border: 2px solid #fdba74; border-radius: 7px; box-shadow: 0 3px 8px rgba(0,0,0,.35); }
|
||||
.cp-seat.loser { border-color: var(--danger); }
|
||||
.cp-head { display: flex; align-items: center; gap: 7px; min-height: 30px; min-width: 0; }
|
||||
.cp-name { font-weight: 800; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; flex: 1; }
|
||||
@@ -354,7 +356,7 @@ function Seat({ id, v, me, players, deadline, bubble }: { id: string; v: Cockroa
|
||||
const role = v.phase === 'finished' ? null : r.holder === id ? (r.peeked ? '넘기는 중' : '받는 중') : r.holder === null && r.starter === id ? '건네는 중' : null;
|
||||
const label = `${u.nickname}님${id === me ? '(나)' : ''}: 손패 ${v.handCounts[id]}장, ${frontText(front, v.loseCount)}${role ? `, ${role}` : ''}${r.seen.includes(id) && r.holder !== null ? ', 이 카드를 봤어요' : ''}${v.away[id] ? ', 자리 비움' : ''}`;
|
||||
return (
|
||||
<section className={`cp-seat${active ? ' turn' : ''}${loser ? ' loser' : ''}`} aria-label={label}>
|
||||
<section className={`cp-seat${active ? ' turn anim-glow' : ''}${loser ? ' loser' : ''}`} data-fx-seat={id} aria-label={label}>
|
||||
{bubble && (
|
||||
<span className="cp-bubble" aria-hidden>
|
||||
{bubble}
|
||||
@@ -705,7 +707,7 @@ function MyArea({
|
||||
const active = waitingOn(v) === me;
|
||||
const total = v.handCounts[me] ?? 0;
|
||||
return (
|
||||
<section className={`cp-me${active ? ' turn' : ''}`} aria-label="내 자리">
|
||||
<section className={`cp-me${active ? ' turn anim-glow' : ''}`} data-fx-seat={me} aria-label="내 자리">
|
||||
{bubble && (
|
||||
<span className="cp-bubble" aria-hidden>
|
||||
{bubble}
|
||||
@@ -752,7 +754,15 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const [bubbles, setBubbles] = useState<Record<string, string>>({});
|
||||
const [fresh, setFresh] = useState({ slide: false, flip: false });
|
||||
const prev = useRef({ claims: v.round.claims.length + v.round.no * 100, reveal: v.lastReveal?.round ?? 0, said: v.said[v.said.length - 1]?.seq ?? 0, waiting: waitingOn(v) });
|
||||
const [banner, showBanner] = useBanner();
|
||||
const prev = useRef({
|
||||
claims: v.round.claims.length + v.round.no * 100,
|
||||
reveal: v.lastReveal?.round ?? 0,
|
||||
said: v.said[v.said.length - 1]?.seq ?? 0,
|
||||
waiting: waitingOn(v),
|
||||
peek: `${v.round.no}:${v.round.seen.length}`,
|
||||
over: v.phase === 'finished',
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const p = prev.current;
|
||||
@@ -763,6 +773,37 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
let msg = '';
|
||||
const slide = claimsKey !== p.claims && v.round.holder !== null;
|
||||
const flip = revealKey !== p.reveal && !!v.lastReveal;
|
||||
const peekKey = `${v.round.no}:${v.round.seen.length}`;
|
||||
const over = v.phase === 'finished';
|
||||
// Sounds + motion (2026-10-13): the same diff drives everyone's moves, so other players' and computers' moves show too.
|
||||
if (slide && v.round.lastPasser && v.round.holder) {
|
||||
flyGhost(seatEl(v.round.lastPasser), seatEl(v.round.holder), { ms: 460, className: 'cp-ghost' });
|
||||
sfx.cardDeal();
|
||||
cpSfx.sneak(80);
|
||||
} else if (!flip && peekKey !== p.peek && v.round.peeked) {
|
||||
sfx.cardFlip(); // someone takes a secret look before passing on
|
||||
}
|
||||
if (flip) {
|
||||
const rv = v.lastReveal!;
|
||||
sfx.cardFlip();
|
||||
setTimeout(() => (rv.correct ? sfx.good() : cpSfx.wrong()), 260);
|
||||
showBanner(rv.call === 'true' ? '진짜!' : '거짓말!', rv.correct ? 'green' : 'red', `${rv.caller === me ? '내가' : `${nick(players, rv.caller)}님이`} ${rv.correct ? '맞혔어요' : '틀렸어요'}`);
|
||||
flyGhost(document.querySelector('.cp-table'), seatEl(rv.takenBy), { delay: 380, ms: 480, className: 'cp-ghost' });
|
||||
setTimeout(() => {
|
||||
bump(seatEl(rv.takenBy), 'shake');
|
||||
const n = v.fronts[rv.takenBy]?.counts[rv.kind] ?? 0;
|
||||
if (!over && n >= v.loseCount - 1) cpSfx.danger();
|
||||
else cpSfx.splat();
|
||||
}, 820);
|
||||
}
|
||||
if (over && !p.over && v.final) {
|
||||
const f = v.final;
|
||||
setTimeout(() => {
|
||||
showBanner(`${f.loser === me ? '내가' : `${nick(players, f.loser)}님`} 패배!`, 'dark', f.losingKind ? `${KIND_KO[f.losingKind]}${hasBatchim(KIND_KO[f.losingKind]) ? '이' : '가'} 너무 많아요` : undefined);
|
||||
cpSfx.danger();
|
||||
bump(seatEl(f.loser), 'shake');
|
||||
}, flip ? 1300 : 0);
|
||||
}
|
||||
if (flip) {
|
||||
const rv = v.lastReveal!;
|
||||
msg = `${nick(players, rv.caller)}님이 ${rv.call === 'true' ? '진짜라고' : '거짓말이라고'} 했고 ${rv.correct ? '맞혔어요' : '틀렸어요'}. ${kj(rv.kind, '은', '는')} ${nick(players, rv.takenBy)}님 앞마당으로 갔어요.`;
|
||||
@@ -779,10 +820,11 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
if (lastSaid > p.said) {
|
||||
const add: Record<string, string> = {};
|
||||
for (const s of v.said) if (s.seq > p.said) add[s.player] = PHRASE_KO[s.phrase];
|
||||
sfx.pop();
|
||||
setBubbles((b) => ({ ...b, ...add }));
|
||||
setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in add)))), 3500);
|
||||
}
|
||||
prev.current = { claims: claimsKey, reveal: revealKey, said: lastSaid, waiting: w };
|
||||
prev.current = { claims: claimsKey, reveal: revealKey, said: lastSaid, waiting: w, peek: peekKey, over };
|
||||
if (slide || flip) {
|
||||
setFresh({ slide, flip });
|
||||
const t = setTimeout(() => setFresh({ slide: false, flip: false }), 700);
|
||||
@@ -818,10 +860,34 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{banner}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 바퀴벌레 포커 sounds on top of the shared palette (synthesized, no files). */
|
||||
const cpSfx = {
|
||||
/** The card slides over with a little scuttle. */
|
||||
sneak: (delay = 0) => {
|
||||
for (let i = 0; i < 4; i++) noise(25, 0.05, delay + i * 45, 'bandpass', 3200 + i * 300, 2);
|
||||
},
|
||||
/** Wrong guess: a sour "bwomp". */
|
||||
wrong: () => {
|
||||
tone(260, 160, 'sawtooth', 0.05, 0, { slideTo: 180 });
|
||||
tone(180, 260, 'sawtooth', 0.05, 150, { slideTo: 110 });
|
||||
},
|
||||
/** The card lands face up in front of someone: a soft "splat". */
|
||||
splat: () => {
|
||||
noise(90, 0.12, 0, 'lowpass', 600);
|
||||
tone(140, 90, 'sine', 0.12, 0, { slideTo: 90 });
|
||||
},
|
||||
/** One more of that critter and you lose (or you just lost). */
|
||||
danger: () => {
|
||||
[880, 660, 880].forEach((f, i) => tone(f, 110, 'square', 0.05, i * 130));
|
||||
tone(110, 400, 'sawtooth', 0.04, 0, { slideTo: 70 });
|
||||
},
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function CockroachSide({ view: v, me, players, act, pending, deadline }: BoardProps<CockroachView>) {
|
||||
@@ -956,7 +1022,7 @@ function statusText(v: CockroachView, me: string | null, players: Record<string,
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
return (
|
||||
<div className="segmented" role="group" aria-label={label}>
|
||||
{options.map(([k, l]) => (
|
||||
@@ -986,7 +1052,7 @@ function Options({ value: o, onChange }: OptionsProps<CockroachOptions>) {
|
||||
<Seg label="같은 벌레 몇 장이면 패배" value={o.loseCount} options={[['auto', '자동(2명 5장, 3~6명 4장)'], [3, '3장(짧게)'], [4, '4장'], [5, '5장']]} onChange={(loseCount) => set({ loseCount })} />
|
||||
</Field>
|
||||
<Field label="건네기·판정 제한 시간">
|
||||
<Seg label="건네기·판정 제한 시간" value={o.turnSeconds} options={[[15, '15초'], [30, '30초'], [60, '60초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||
<Seg label="건네기·판정 제한 시간" value={o.turnSeconds} options={[[15, '15초'], [30, '30초'], [60, '60초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||
</Field>
|
||||
<Field label="이번 라운드 주장 기록">
|
||||
<Seg label="이번 라운드 주장 기록" value={o.claimHistory} options={[[true, '보이기'], [false, '숨기기']]} onChange={(claimHistory) => set({ claimHistory })} />
|
||||
@@ -1015,7 +1081,7 @@ function optionsSummary(o: CockroachOptions, players?: number): string {
|
||||
const lose = o.loseCount === 'auto' ? (players ? `${players === 2 ? 5 : 4}장` : '자동(2명 5장, 그 외 4장)') : `${o.loseCount}장`;
|
||||
return [
|
||||
`같은 벌레 ${lose}이면 패배`,
|
||||
`제한 ${o.turnSeconds}초`,
|
||||
o.turnSeconds === null ? '시간 무제한' : `제한 ${o.turnSeconds}초`,
|
||||
...(o.claimHistory ? [] : ['주장 기록 숨김']),
|
||||
...(o.quickChat ? [] : ['빠른 말 끔']),
|
||||
...(o.eightKindsRule ? ['8종 모으면 패배'] : []),
|
||||
@@ -1058,7 +1124,7 @@ function Rules({ options }: { options?: CockroachOptions }) {
|
||||
<p>카드를 앞마당에 놓은 사람이 다음 라운드를 시작해요. 그때 손에 카드가 한 장도 없으면 바로 져요.</p>
|
||||
{o?.eightKindsRule && <p>하우스 룰: 앞마당에 8종을 모두 한 장 이상 모아도 져요.</p>}
|
||||
<p className="muted">
|
||||
시간 안에 고르지 않으면 자동으로 진행돼요(건네기: 무작위 카드를 다음 사람에게, 판정: 무작위, 넘기기: 아직 안 본 다음 사람에게 실제 벌레 이름으로). 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요. 게임을 나가면 그 사람이 진
|
||||
{o?.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 고르지 않으면'} 자동으로 진행돼요(건네기: 무작위 카드를 다음 사람에게, 판정: 무작위, 넘기기: 아직 안 본 다음 사람에게 실제 벌레 이름으로). 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요. 게임을 나가면 그 사람이 진
|
||||
것으로 끝나요.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
30
apps/web/src/games/connect-four/help.test.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { expect, test } from 'bun:test';
|
||||
import { applyAction, setupGame, usersOf } from '../help-kit.test-util';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { helpNow } from './help';
|
||||
|
||||
const users = usersOf(['A', 'B']);
|
||||
const view = (s: unknown, who: string | null) => GAMES['connect-four']!.view(s, who) as any;
|
||||
|
||||
test('커넥트 포: 내 차례 / 상대 차례 / 관전 / 꽉 찬 열', () => {
|
||||
const { state } = setupGame('connect-four', 2, { colorAssignment: 'hostRed' });
|
||||
const first = helpNow(view(state, 'A'), 'A', users);
|
||||
expect(first).toContain('내 차례예요(빨강)');
|
||||
expect(first).toContain('가운데 열');
|
||||
expect(helpNow(view(state, 'B'), 'B', users)).toContain('상대(호랑이님) 차례예요');
|
||||
expect(helpNow(view(state, null), null, users)).toContain('호랑이님(빨강) 차례예요');
|
||||
let s = state;
|
||||
for (let i = 0; i < 6; i++) s = applyAction('connect-four', s, i % 2 ? 'B' : 'A', { type: 'drop', col: 0 });
|
||||
const t = helpNow(view(s, 'A'), 'A', users);
|
||||
expect(t).toContain('1열은 꽉 차서');
|
||||
expect(t).toContain('4개');
|
||||
});
|
||||
|
||||
test('커넥트 포: 끝난 판은 결과와 다시 하기 안내', () => {
|
||||
const { state } = setupGame('connect-four', 2, { colorAssignment: 'hostRed' });
|
||||
let s = state;
|
||||
for (const [who, col] of [['A', 0], ['B', 0], ['A', 1], ['B', 1], ['A', 2], ['B', 2], ['A', 3]] as const) s = applyAction('connect-four', s, who, { type: 'drop', col });
|
||||
const t = helpNow(view(s, 'B'), 'B', users);
|
||||
expect(t).toContain('빨강 승');
|
||||
expect(t).toContain('[한 판 더]');
|
||||
});
|
||||
20
apps/web/src/games/connect-four/help.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
/** 커넥트 포 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { ConnectFourView } from '@bg/games/connect-four';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
|
||||
const COLOR_KO = { red: '빨강', yellow: '노랑' } as const;
|
||||
|
||||
export function helpNow(v: ConnectFourView, _me: string | null, players: Record<string, PublicUser>): string {
|
||||
const goal = '가로·세로·대각선 중 한 줄로 내 돌 4개를 먼저 이으면 이겨요.';
|
||||
if (v.phase === 'finished') return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n결과 창에서 [한 판 더]를 누르면 다시 할 수 있어요.';
|
||||
const turnNick = players[v.players[v.turn]]?.nickname ?? COLOR_KO[v.turn];
|
||||
if (!v.myColor) return `${turnNick}님(${COLOR_KO[v.turn]}) 차례예요. ${goal}`;
|
||||
const mine = COLOR_KO[v.myColor];
|
||||
if (v.myColor !== v.turn) return `상대(${turnNick}님) 차례예요. 상대가 돌을 넣을 때까지 기다려 주세요. 나는 ${mine}이에요.`;
|
||||
const full = Array.from({ length: v.cols }, (_, c) => c).filter((c) => v.board[c] !== 0);
|
||||
const lines = [`내 차례예요(${mine}). 돌을 넣을 열을 눌러요. 돌은 그 열의 맨 아래 빈칸까지 떨어져요. ${goal}`];
|
||||
if (v.moveCount === 0) lines.push('처음에는 가운데 열에 넣는 게 좋아요. 가운데일수록 4개를 이을 길이 많아요.');
|
||||
if (full.length) lines.push(`${full.map((c) => `${c + 1}열`).join(', ')}은 꽉 차서 넣을 수 없어요.`);
|
||||
lines.push('상대가 3개를 이어 놓았다면 남은 한 칸을 먼저 막아요.');
|
||||
return lines.join('\n');
|
||||
}
|
||||
460
apps/web/src/games/connect-four/index.tsx
Normal file
@@ -0,0 +1,460 @@
|
||||
/** 커넥트 포 화면 (docs/games/connect-four.md §9). */
|
||||
import { useEffect, useId, useRef, useState } from 'react';
|
||||
import type { Color, ConnectFourOptions, ConnectFourView } from '@bg/games/connect-four';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet } from '../../components/ui';
|
||||
import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, noise, sfx, tone } from '../../lib/feedback';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
const COLOR_KO: Record<Color, string> = { red: '빨강', yellow: '노랑' };
|
||||
const FILL: Record<Color, [string, string]> = { red: ['#dc2626', '#991b1b'], yellow: ['#facc15', '#b45309'] };
|
||||
const SIZE_KO: Record<ConnectFourOptions['boardSize'], string> = { '7x6': '7×6', '8x7': '8×7', '9x7': '9×7' };
|
||||
/** Row counted from the bottom, 1-based (what people say: "아래에서 두 번째 줄"). */
|
||||
const rowFromBottom = (v: ConnectFourView, y: number) => v.rows - y;
|
||||
|
||||
/** Falls with gravity, hits the bottom at LAND (fraction of the animation), bounces once a little and settles. */
|
||||
const LAND = 0.78;
|
||||
/** Fall time for a disc that lands in row `y` (0 = top). */
|
||||
const fallSec = (y: number) => (0.16 + 0.06 * (y + 1)) / LAND;
|
||||
const CSS = `
|
||||
@keyframes c4drop {
|
||||
0% { transform: translateY(var(--c4-from)); animation-timing-function: cubic-bezier(.5, 0, 1, 1); }
|
||||
${LAND * 100}% { transform: translateY(0); animation-timing-function: ease-out; }
|
||||
89% { transform: translateY(-0.13px); animation-timing-function: ease-in; }
|
||||
100% { transform: translateY(0); }
|
||||
}
|
||||
.c4-drop { animation: c4drop var(--c4-dur) linear both; }
|
||||
@keyframes c4glow { 50% { opacity: .35; } }
|
||||
.c4-win { animation: c4glow 1.1s ease-in-out infinite; animation-delay: var(--c4-delay, 0ms); }
|
||||
.c4-svg { --c4-frame: #1d4ed8; --c4-frame-edge: #1e3a8a; }
|
||||
:root[data-theme='dark'] .c4-svg { --c4-frame: #1e40af; --c4-frame-edge: #172554; }
|
||||
@media (prefers-color-scheme: dark) { :root[data-theme='auto'] .c4-svg { --c4-frame: #1e40af; --c4-frame-edge: #172554; } }
|
||||
@media (prefers-reduced-motion: reduce) { .c4-drop, .c4-win { animation: none; } }
|
||||
`;
|
||||
|
||||
function Disc({ color, cx, cy, r, ghost }: { color: Color; cx: number; cy: number; r: number; ghost?: boolean }) {
|
||||
const [fill, edge] = FILL[color];
|
||||
return (
|
||||
<g opacity={ghost ? 0.5 : 1}>
|
||||
<circle cx={cx} cy={cy} r={r} fill={fill} stroke={edge} strokeWidth={0.05} />
|
||||
<circle cx={cx} cy={cy} r={r * 0.68} fill="none" stroke={edge} strokeWidth={0.05} opacity={0.45} />
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
function C4Board({ view: v, act, pending, tapConfirm }: BoardProps<ConnectFourView>) {
|
||||
const { cols, rows } = v;
|
||||
const myTurn = v.phase === 'playing' && v.myColor === v.turn;
|
||||
const [preview, setPreview] = useState<number | null>(null);
|
||||
const [hover, setHover] = useState<number | null>(null);
|
||||
const [cursor, setCursor] = useState(Math.floor((cols - 1) / 2));
|
||||
const [kbd, setKbd] = useState(false);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const maskId = `c4mask${useId().replace(/:/g, '')}`;
|
||||
const prevCount = useRef(v.moveCount);
|
||||
const prevTurn = useRef(v.turn);
|
||||
// The disc dropped since the last render falls in (only for moves seen live, not on page load).
|
||||
const seen = useRef(v.moveCount);
|
||||
const falling = useRef<number | null>(null);
|
||||
if (v.moveCount > seen.current) falling.current = v.moveCount;
|
||||
seen.current = v.moveCount;
|
||||
|
||||
useEffect(() => {
|
||||
if (v.moveCount > prevCount.current && v.lastMove) {
|
||||
// A light rattle as it leaves the hand, then the plastic clack when it hits the bottom (and a small second tap).
|
||||
const land = fallSec(v.lastMove.y) * LAND * 1000;
|
||||
noise(Math.min(160, land), 0.04, 0, 'bandpass', 1800, 0.7);
|
||||
tone(620, 70, 'triangle', 0.2, land);
|
||||
noise(45, 0.12, land, 'lowpass', 1400);
|
||||
tone(760, 40, 'triangle', 0.07, land + 110);
|
||||
const m = v.moves[v.moves.length - 1]!;
|
||||
setAnnounce(`${COLOR_KO[m.color]}이 ${m.x + 1}열에 넣었어요. 아래에서 ${rowFromBottom(v, m.y)}번째 칸이에요.${m.auto ? ' (시간이 다 돼서 자동으로)' : ''}`);
|
||||
}
|
||||
if (v.phase === 'playing' && myTurn && prevTurn.current !== v.turn && v.moveCount !== prevCount.current) haptic(40);
|
||||
prevCount.current = v.moveCount;
|
||||
prevTurn.current = v.turn;
|
||||
setPreview(null);
|
||||
}, [v.moveCount, v.turn]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const open = (c: number) => v.board[c] === 0;
|
||||
const canDrop = (c: number) => myTurn && !pending && open(c);
|
||||
const landing = (c: number) => {
|
||||
for (let y = rows - 1; y >= 0; y--) if (v.board[y * cols + c] === 0) return y;
|
||||
return -1;
|
||||
};
|
||||
|
||||
const drop = (c: number) => {
|
||||
act({ type: 'drop', col: c });
|
||||
setPreview(null);
|
||||
setHover(null);
|
||||
};
|
||||
|
||||
const tap = (c: number, mouse: boolean) => {
|
||||
setCursor(c);
|
||||
setKbd(false);
|
||||
if (!myTurn) return;
|
||||
if (!open(c)) {
|
||||
haptic([30, 30, 30]);
|
||||
sfx.bad();
|
||||
setAnnounce(`${c + 1}열은 꽉 찼어요. 다른 열을 골라 주세요.`);
|
||||
return;
|
||||
}
|
||||
// Mouse: one click drops (hover already shows where). Touch: optional two-step confirm.
|
||||
if (mouse || !tapConfirm) {
|
||||
if (canDrop(c)) drop(c);
|
||||
return;
|
||||
}
|
||||
if (preview === c) drop(c);
|
||||
else setPreview(c);
|
||||
};
|
||||
|
||||
const onKey = (e: React.KeyboardEvent) => {
|
||||
setKbd(true);
|
||||
const step: Record<string, number> = { ArrowLeft: -1, ArrowRight: 1 };
|
||||
if (step[e.key]) {
|
||||
e.preventDefault();
|
||||
setCursor((c) => Math.min(cols - 1, Math.max(0, c + step[e.key]!)));
|
||||
} else if (e.key === 'Home' || e.key === 'End') {
|
||||
e.preventDefault();
|
||||
setCursor(e.key === 'Home' ? 0 : cols - 1);
|
||||
} else if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
if (canDrop(cursor)) drop(cursor);
|
||||
else if (myTurn && !open(cursor)) setAnnounce(`${cursor + 1}열은 꽉 찼어요.`);
|
||||
}
|
||||
};
|
||||
|
||||
const ghostCol = preview ?? (hover !== null && canDrop(hover) ? hover : myTurn && kbd && open(cursor) ? cursor : null);
|
||||
const ghostLand = ghostCol !== null ? landing(ghostCol) : -1;
|
||||
const winSet = new Set((v.winLine ?? []).map((p) => p.y * cols + p.x));
|
||||
const last = v.lastMove ? v.lastMove.y * cols + v.lastMove.x : -1;
|
||||
const pad = 0.15;
|
||||
const cells = Array.from({ length: cols * rows }, (_, i) => i);
|
||||
return (
|
||||
<div className="board-wrap stack" style={{ gap: 10, maxWidth: `min(100%, calc((100vh - var(--site-h, 56px) - 180px) * ${(cols + 2 * pad) / (rows + 1.6)}))` }}>
|
||||
<style>{CSS}</style>
|
||||
<svg
|
||||
className="c4-svg"
|
||||
viewBox={`${-pad} -1.1 ${cols + 2 * pad} ${rows + 1.1 + 0.6}`}
|
||||
style={{ width: '100%', display: 'block', touchAction: 'manipulation', cursor: myTurn ? 'pointer' : 'default', userSelect: 'none' }}
|
||||
onPointerLeave={() => setHover(null)}
|
||||
tabIndex={0}
|
||||
role="grid"
|
||||
aria-label={`커넥트 포 판 ${cols}열 ${rows}줄. 왼쪽·오른쪽 화살표로 열을 고르고 Enter로 돌을 넣어요. 지금 고른 열: ${cursor + 1}열${open(cursor) ? '' : '(꽉 참)'}`}
|
||||
onKeyDown={onKey}
|
||||
>
|
||||
<defs>
|
||||
<mask id={maskId}>
|
||||
<rect x={-pad} y={-pad} width={cols + 2 * pad} height={rows + 2 * pad} fill="white" />
|
||||
{cells.map((i) => (
|
||||
<circle key={i} cx={(i % cols) + 0.5} cy={Math.floor(i / cols) + 0.5} r={0.42} fill="black" />
|
||||
))}
|
||||
</mask>
|
||||
</defs>
|
||||
{/* Holes, then discs (behind the frame, so a falling disc shows through the holes), then the frame. */}
|
||||
<rect x={0} y={0} width={cols} height={rows} fill="var(--bg)" />
|
||||
{ghostCol !== null && ghostLand >= 0 && (
|
||||
<circle cx={ghostCol + 0.5} cy={ghostLand + 0.5} r={0.36} fill="none" stroke={v.myColor ? FILL[v.myColor][0] : '#888'} strokeWidth={0.07} strokeDasharray="0.14 0.1" />
|
||||
)}
|
||||
{cells.map((i) => {
|
||||
const c = v.board[i];
|
||||
if (!c) return null;
|
||||
const x = i % cols;
|
||||
const y = Math.floor(i / cols);
|
||||
const anim = i === last && falling.current === v.moveCount;
|
||||
return (
|
||||
<g
|
||||
key={i}
|
||||
className={anim ? 'c4-drop' : undefined}
|
||||
style={anim ? ({ '--c4-from': `${-(y + 1.5)}px`, '--c4-dur': `${fallSec(y)}s` } as React.CSSProperties) : undefined}
|
||||
>
|
||||
<Disc color={c === 1 ? 'red' : 'yellow'} cx={x + 0.5} cy={y + 0.5} r={0.41} />
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
<rect x={-pad} y={-pad} width={cols + 2 * pad} height={rows + 2 * pad} rx={0.3} fill="var(--c4-frame)" stroke="var(--c4-frame-edge)" strokeWidth={0.05} mask={`url(#${maskId})`} />
|
||||
{last >= 0 && !winSet.size && (
|
||||
// Shown once the falling disc has landed.
|
||||
<circle
|
||||
key={`lm${v.moveCount}`}
|
||||
className={falling.current === v.moveCount ? 'anim-pop' : undefined}
|
||||
style={{ '--anim-delay': `${fallSec(Math.floor(last / cols)) * 1000}ms`, transformBox: 'fill-box', transformOrigin: 'center' } as React.CSSProperties}
|
||||
cx={(last % cols) + 0.5}
|
||||
cy={Math.floor(last / cols) + 0.5}
|
||||
r={0.09}
|
||||
fill="#fff"
|
||||
opacity={0.85}
|
||||
/>
|
||||
)}
|
||||
{(v.winLine ?? []).map((p, k) => (
|
||||
<circle
|
||||
key={`w${p.x}-${p.y}`}
|
||||
className="c4-win"
|
||||
style={{ '--c4-delay': `${k * 120}ms` } as React.CSSProperties}
|
||||
cx={p.x + 0.5}
|
||||
cy={p.y + 0.5}
|
||||
r={0.36}
|
||||
fill="none"
|
||||
stroke="#fff"
|
||||
strokeWidth={0.1}
|
||||
/>
|
||||
))}
|
||||
{ghostCol !== null && v.myColor && <Disc color={v.myColor} cx={ghostCol + 0.5} cy={-0.55} r={0.41} ghost={preview === null} />}
|
||||
{myTurn && kbd && <rect x={cursor + 0.04} y={-1.08} width={0.92} height={rows + 1.04} rx={0.12} fill="none" stroke="var(--focus)" strokeWidth={0.07} />}
|
||||
{Array.from({ length: cols }, (_, c) => (
|
||||
<text key={`l${c}`} x={c + 0.5} y={rows + 0.42} fontSize={0.34} fontWeight={700} textAnchor="middle" dominantBaseline="central" fill="var(--text-sub)">
|
||||
{c + 1}
|
||||
</text>
|
||||
))}
|
||||
{/* Tap areas: the whole column, header row included. */}
|
||||
{Array.from({ length: cols }, (_, c) => (
|
||||
<rect
|
||||
key={`t${c}`}
|
||||
data-col={c}
|
||||
x={c}
|
||||
y={-1.1}
|
||||
width={1}
|
||||
height={rows + 1.1}
|
||||
fill="transparent"
|
||||
onPointerMove={(e) => {
|
||||
if (e.pointerType === 'mouse' && myTurn && hover !== c) setHover(c);
|
||||
}}
|
||||
onPointerUp={(e) => tap(c, e.pointerType === 'mouse')}
|
||||
/>
|
||||
))}
|
||||
</svg>
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{preview !== null && myTurn && (
|
||||
<div className="row" style={{ justifyContent: 'center' }}>
|
||||
<button className="btn btn-primary" style={{ flex: 2 }} disabled={!canDrop(preview)} onClick={() => drop(preview)}>
|
||||
{`${preview + 1}열에 넣기`}
|
||||
</button>
|
||||
<button className="btn btn-secondary" style={{ flex: 1 }} onClick={() => setPreview(null)}>
|
||||
취소
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Right-hand panel on PC (below the board on narrow screens). */
|
||||
function C4Side({ view: v, me, players, act, deadline }: BoardProps<ConnectFourView>) {
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
const opp: Color = v.myColor === 'yellow' ? 'red' : 'yellow';
|
||||
const mine: Color = v.myColor ?? 'red';
|
||||
return (
|
||||
<>
|
||||
<PlayerBar view={v} color={v.myColor ? opp : 'red'} players={players} deadline={deadline} me={me} />
|
||||
<PlayerBar view={v} color={v.myColor ? mine : 'yellow'} players={players} deadline={deadline} me={me} />
|
||||
{v.phase === 'playing' && v.myColor && (
|
||||
<button className="btn btn-danger btn-sm" onClick={() => setConfirm(true)}>
|
||||
🏳 기권
|
||||
</button>
|
||||
)}
|
||||
<MoveList view={v} />
|
||||
{confirm && <ConfirmSheet title="기권할까요?" body="기권하면 이 판은 상대가 이겨요." confirm="기권하기" danger onConfirm={() => act({ type: 'resign' })} onClose={() => setConfirm(false)} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function MoveList({ view: v }: { view: ConnectFourView }) {
|
||||
const ref = useRef<HTMLOListElement>(null);
|
||||
useEffect(() => {
|
||||
ref.current?.scrollTo({ top: ref.current.scrollHeight });
|
||||
}, [v.moveCount]);
|
||||
if (v.moveCount === 0) return null;
|
||||
return (
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기보 ({v.moveCount}수)</summary>
|
||||
<ol ref={ref} style={{ margin: '8px 0 0', paddingLeft: 0, listStyle: 'none', maxHeight: 132, overflow: 'auto', display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '2px 8px', fontVariantNumeric: 'tabular-nums' }}>
|
||||
{v.moves.map((m, i) => (
|
||||
<li key={i} className="small">
|
||||
<span className="muted">{i + 1}.</span> <span aria-label={COLOR_KO[m.color]}>{m.color === 'red' ? '🔴' : '🟡'}</span> {m.x + 1}열
|
||||
{m.auto ? '*' : ''}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
function PlayerBar({ view: v, color, players, deadline, me }: { view: ConnectFourView; color: Color; players: Record<string, PublicUser>; deadline: number | null; me: string | null }) {
|
||||
const id = v.players[color];
|
||||
const u = players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' as const };
|
||||
const active = v.phase === 'playing' && v.turn === color;
|
||||
const now = useServerNow(500);
|
||||
const tc = v.timeControl;
|
||||
let clock: React.ReactNode = null;
|
||||
if (tc.kind === 'fischer') {
|
||||
const ms = Math.max(0, v.remainingMs[color] - (active ? now - v.turnStartedAt : 0));
|
||||
const s = Math.ceil(ms / 1000);
|
||||
clock = (
|
||||
<span style={{ fontVariantNumeric: 'tabular-nums', fontWeight: 700, fontSize: '1.15rem', color: active && s <= 10 ? 'var(--danger)' : undefined }}>
|
||||
{Math.floor(s / 60)}:{String(s % 60).padStart(2, '0')}
|
||||
</span>
|
||||
);
|
||||
} else if (active && tc.kind === 'perMove') {
|
||||
clock = <TurnTimer deadline={deadline} totalMs={tc.perMoveSec * 1000} mine={id === me} />;
|
||||
}
|
||||
return (
|
||||
<div className="card row" style={{ padding: '8px 12px', gap: 10, border: `3px solid ${active ? 'var(--primary)' : 'transparent'}`, transition: 'border-color 0.2s' }}>
|
||||
<svg width={28} height={28} viewBox="-1 -1 2 2" aria-hidden>
|
||||
<Disc color={color} cx={0} cy={0} r={0.9} />
|
||||
</svg>
|
||||
<Avatar user={u} size={32} />
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||||
{u.nickname}
|
||||
{id === me && <span className="muted small"> (나)</span>}
|
||||
</div>
|
||||
<div className="muted small">
|
||||
{COLOR_KO[color]}
|
||||
{color === 'red' ? ' · 먼저' : ' · 나중'}
|
||||
{active ? ' · 두는 중' : ''}
|
||||
</div>
|
||||
</div>
|
||||
{clock}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function statusText(v: ConnectFourView, _me: string | null, players: Record<string, PublicUser>): string {
|
||||
if (v.phase === 'finished') return v.result?.summary ?? '게임이 끝났어요';
|
||||
if (v.myColor === v.turn) return `내 차례예요 (${COLOR_KO[v.turn]}). 돌을 넣을 열을 눌러 주세요`;
|
||||
const nick = players[v.players[v.turn]]?.nickname ?? COLOR_KO[v.turn];
|
||||
return v.myColor ? `${nick}님이 생각 중이에요…` : `${nick}님(${COLOR_KO[v.turn]}) 차례예요`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
function Seg<T extends string | number>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
return (
|
||||
<div className="segmented" role="group" aria-label={label}>
|
||||
{options.map(([k, l]) => (
|
||||
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type TimeControl = ConnectFourOptions['timeControl'];
|
||||
const TIME_PRESETS: [string, string, Partial<TimeControl>][] = [
|
||||
['pm10', '한 수 10초', { kind: 'perMove', perMoveSec: 10 }],
|
||||
['pm20', '한 수 20초', { kind: 'perMove', perMoveSec: 20 }],
|
||||
['pm30', '한 수 30초', { kind: 'perMove', perMoveSec: 30 }],
|
||||
['pm60', '한 수 60초', { kind: 'perMove', perMoveSec: 60 }],
|
||||
['f1', '1분 + 2초', { kind: 'fischer', baseSec: 60, incSec: 2 }],
|
||||
['f3', '3분 + 2초', { kind: 'fischer', baseSec: 180, incSec: 2 }],
|
||||
['f5', '5분 + 3초', { kind: 'fischer', baseSec: 300, incSec: 3 }],
|
||||
['none', '시간 제한 없음', { kind: 'none' }],
|
||||
];
|
||||
|
||||
function timeKey(tc: TimeControl): string {
|
||||
if (tc.kind === 'none') return 'none';
|
||||
if (tc.kind === 'perMove') return `pm${tc.perMoveSec}`;
|
||||
return `f${Math.round(tc.baseSec / 60)}`;
|
||||
}
|
||||
|
||||
function timeLabel(tc: TimeControl): string {
|
||||
if (tc.kind === 'none') return '시간 제한 없음';
|
||||
if (tc.kind === 'perMove') return `한 수 ${tc.perMoveSec}초`;
|
||||
const m = Math.floor(tc.baseSec / 60);
|
||||
const sec = tc.baseSec % 60;
|
||||
return `${m}분${sec ? ` ${sec}초` : ''} + ${tc.incSec}초`;
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<ConnectFourOptions>) {
|
||||
const [more, setMore] = useState(false);
|
||||
const set = (patch: Partial<ConnectFourOptions>) => onChange({ ...o, ...patch });
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>판 크기 (가로 × 세로)</strong>
|
||||
<Seg label="판 크기" value={o.boardSize} options={[['7x6', '7 × 6 (기본)'], ['8x7', '8 × 7'], ['9x7', '9 × 7']]} onChange={(boardSize) => set({ boardSize })} />
|
||||
</div>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>시간</strong>
|
||||
<Seg
|
||||
label="시간"
|
||||
value={timeKey(o.timeControl)}
|
||||
options={[
|
||||
...TIME_PRESETS.map(([k, l]) => [k, l] as [string, string]),
|
||||
...(TIME_PRESETS.some((p) => p[0] === timeKey(o.timeControl)) ? [] : [[timeKey(o.timeControl), `${timeLabel(o.timeControl)}(관리자 설정)`] as [string, string]]),
|
||||
]}
|
||||
onChange={(k) => {
|
||||
const preset = TIME_PRESETS.find((p) => p[0] === k);
|
||||
if (preset) set({ timeControl: { ...o.timeControl, ...preset[2] } });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>빨강(먼저 두는 쪽)</strong>
|
||||
<Seg
|
||||
label="먼저 두는 사람"
|
||||
value={o.colorAssignment}
|
||||
options={[['random', '무작위'], ['hostRed', '방장이 먼저'], ['hostYellow', '방장이 나중'], ['alternate', '판마다 번갈아']]}
|
||||
onChange={(colorAssignment) => set({ colorAssignment })}
|
||||
/>
|
||||
</div>
|
||||
{o.timeControl.kind === 'perMove' && (
|
||||
<>
|
||||
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
|
||||
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
|
||||
</button>
|
||||
{more && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>시간이 다 되면</strong>
|
||||
<Seg label="시간이 다 되면" value={o.timeoutPolicy} options={[['autoMove', '자동으로 두기'], ['lose', '시간패']]} onChange={(timeoutPolicy) => set({ timeoutPolicy })} />
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: ConnectFourOptions): string {
|
||||
const first = o.colorAssignment === 'alternate' ? '선 번갈아' : o.colorAssignment === 'hostRed' ? '방장 먼저' : o.colorAssignment === 'hostYellow' ? '방장 나중' : '선 무작위';
|
||||
return [`${SIZE_KO[o.boardSize]} 판`, timeLabel(o.timeControl), first].join(' · ');
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: ConnectFourOptions }) {
|
||||
const size = options?.boardSize ?? '7x6';
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
세워 놓은 {SIZE_KO[size]} 판에 빨강과 노랑이 번갈아 돌을 넣어요. <strong>열을 고르면 돌이 그 열의 맨 아래 빈칸까지 떨어져요.</strong> 빨강이 먼저 둬요.
|
||||
</p>
|
||||
<p>
|
||||
가로, 세로, 대각선 중 한 줄로 내 돌 <strong>4개</strong>를 먼저 이으면 바로 이겨요. 판이 다 찰 때까지 아무도 못 이으면 비겨요.
|
||||
</p>
|
||||
<p>꽉 찬 열에는 넣을 수 없어요. 내가 넣은 돌 바로 위 칸은 상대가 쓸 수 있으니, 상대가 이기는 칸을 받쳐 주지 않게 조심해요.</p>
|
||||
<p>
|
||||
PC에서는 열을 누르거나 키보드 ←·→로 열을 고르고 Enter를 눌러요. 휴대폰에서는 열 아무 곳이나 누르면 돼요(한 번 더 누르기 확인을 켰다면 같은 열을 한 번 더 누르거나 [넣기]를 눌러요).
|
||||
</p>
|
||||
{options?.timeControl.kind === 'perMove' && options.timeoutPolicy === 'autoMove' && <p>한 수 시간이 다 되면 컴퓨터가 대신 한 수를 둬요. 여러 번 계속되면 시간패예요.</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<ConnectFourView, ConnectFourOptions> = {
|
||||
Board: C4Board,
|
||||
Side: C4Side,
|
||||
statusText,
|
||||
isMyTurn: (v, me) => v.phase === 'playing' && !!v.myColor && v.players[v.turn] === me,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
52
apps/web/src/games/connect-four/quick.tsx
Normal file
@@ -0,0 +1,52 @@
|
||||
/** 커넥트 포 30초 규칙 요약 (docs/07 §5). */
|
||||
import type { QuickCard } from '../types';
|
||||
|
||||
type D = 'r' | 'y';
|
||||
|
||||
/** Small 7 × 6 board: discs as [column, row from the bottom, colour]; `arrow` marks a column; `ring` circles cells. */
|
||||
function MiniBoard({ discs, arrow, ring = [] }: { discs: [number, number, D][]; arrow?: number; ring?: [number, number][] }) {
|
||||
const cols = 7;
|
||||
const rows = 6;
|
||||
const cy = (h: number) => rows - h - 0.5;
|
||||
return (
|
||||
<svg viewBox="-0.2 -1.2 7.4 7.4" width={180} height={180} aria-hidden>
|
||||
<rect x={-0.15} y={-0.15} width={cols + 0.3} height={rows + 0.3} rx={0.3} fill="#1d4ed8" />
|
||||
{Array.from({ length: cols * rows }, (_, i) => (
|
||||
<circle key={i} cx={(i % cols) + 0.5} cy={Math.floor(i / cols) + 0.5} r={0.4} fill="#f7f5f0" />
|
||||
))}
|
||||
{discs.map(([x, h, c]) => (
|
||||
<circle key={`${x}-${h}`} cx={x + 0.5} cy={cy(h)} r={0.4} fill={c === 'r' ? '#dc2626' : '#facc15'} stroke={c === 'r' ? '#991b1b' : '#b45309'} strokeWidth={0.05} />
|
||||
))}
|
||||
{ring.map(([x, h]) => (
|
||||
<circle key={`g${x}-${h}`} cx={x + 0.5} cy={cy(h)} r={0.34} fill="none" stroke="#fff" strokeWidth={0.1} />
|
||||
))}
|
||||
{arrow !== undefined && (
|
||||
<g fill="#dc2626">
|
||||
<circle cx={arrow + 0.5} cy={-0.7} r={0.38} />
|
||||
<path d={`M ${arrow + 0.25} -0.15 L ${arrow + 0.75} -0.15 L ${arrow + 0.5} 0.15 Z`} />
|
||||
</g>
|
||||
)}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: <MiniBoard discs={[[3, 0, 'y'], [2, 0, 'r']]} arrow={3} />,
|
||||
alt: '세워 놓은 파란 판의 4번째 열 위에 빨간 돌이 있고, 그 열 맨 아래에는 노란 돌이 있어요',
|
||||
title: '열을 골라 넣어요',
|
||||
text: '빨강이 먼저예요. 내 차례에 열을 누르면 돌이 그 열의 맨 아래 빈칸까지 떨어져요.',
|
||||
},
|
||||
{
|
||||
pic: <MiniBoard discs={[[0, 0, 'r'], [1, 0, 'r'], [2, 1, 'r'], [3, 2, 'r'], [4, 3, 'r'], [2, 0, 'y'], [3, 0, 'y'], [3, 1, 'y'], [4, 0, 'y'], [4, 1, 'r'], [4, 2, 'y']]} ring={[[1, 0], [2, 1], [3, 2], [4, 3]]} />,
|
||||
alt: '빨간 돌 4개가 대각선으로 이어져 하얀 테두리로 빛나요',
|
||||
title: '4개를 이으면 이겨요',
|
||||
text: '가로·세로·대각선 어느 쪽이든 내 돌 4개를 먼저 한 줄로 이으면 이겨요. 판이 다 차면 비겨요.',
|
||||
},
|
||||
{
|
||||
pic: <MiniBoard discs={[[1, 0, 'y'], [2, 0, 'y'], [3, 0, 'y'], [3, 1, 'r'], [2, 1, 'r'], [6, 0, 'r']]} ring={[[0, 0], [4, 0]]} />,
|
||||
alt: '맨 아래 줄에 노란 돌 3개가 있고 양쪽 빈칸에 하얀 동그라미가 있어요',
|
||||
title: '3개면 꼭 막아요',
|
||||
text: '상대가 3개를 이으면 남은 칸을 먼저 막아요. 양쪽이 다 비어 있으면 하나밖에 못 막으니 미리 조심해요.',
|
||||
},
|
||||
];
|
||||
@@ -1,10 +1,11 @@
|
||||
/** 달무티 화면 (docs/games/dalmuti.md §9). */
|
||||
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
|
||||
import type { Choice, DCard, DalmutiOptions, DalmutiView, LogEntry, PlayView, SeatView, Title } from '@bg/games/dalmuti';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner, useNewEntries } from '../card-fx';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -51,6 +52,52 @@ const rankText = (rank: number) => (rank === JESTER ? '광대(13)' : String(rank
|
||||
const setText = (p: { rank: number; count: number }) => `${rankText(p.rank)} × ${p.count}장`;
|
||||
const facesText = (cards: number[]) => cards.map((n) => (n === JESTER ? '광대' : String(n))).join(', ');
|
||||
|
||||
/** 달무티 sounds on top of the shared palette (synthesized, no files). */
|
||||
const dmSfx = {
|
||||
/** A set lands on the pile: one slap per card. */
|
||||
set: (n: number) => {
|
||||
for (let i = 0; i < Math.min(n, 6); i++) noise(60, 0.15, i * 55, 'bandpass', 1500 + i * 120, 0.9);
|
||||
tone(220, 70, 'sine', 0.09, Math.min(n - 1, 5) * 55);
|
||||
},
|
||||
/** Soft double knock on the table (pass). */
|
||||
knock: () => {
|
||||
tone(190, 70, 'sine', 0.14);
|
||||
noise(35, 0.06, 0, 'lowpass', 700);
|
||||
tone(165, 70, 'sine', 0.12, 120);
|
||||
noise(35, 0.05, 120, 'lowpass', 700);
|
||||
},
|
||||
/** 혁명 / 대혁명: drum roll, falling growl, then a big chord (higher and longer for 대혁명). */
|
||||
revolution: (great: boolean) => {
|
||||
for (let i = 0; i < 7; i++) noise(90, 0.1 + i * 0.012, i * 55, 'lowpass', 320);
|
||||
tone(130, 520, 'sawtooth', 0.06, 0, { slideTo: great ? 55 : 80 });
|
||||
[392, 494, 587, 784].forEach((f, i) => tone(f, 420, 'square', 0.045, 420 + i * 35));
|
||||
if (great) [523, 659, 784, 1046].forEach((f, i) => tone(f, 520, 'square', 0.045, 820 + i * 35));
|
||||
},
|
||||
/** Tax card slides over (with a little coin ring). */
|
||||
tax: () => {
|
||||
noise(140, 0.1, 0, 'bandpass', 1200, 0.6);
|
||||
tone(660, 80, 'triangle', 0.07, 120);
|
||||
tone(990, 130, 'triangle', 0.06, 190);
|
||||
},
|
||||
/** Card given back: slide + a lower note. */
|
||||
give: () => {
|
||||
noise(140, 0.1, 0, 'bandpass', 1000, 0.6);
|
||||
tone(520, 110, 'triangle', 0.06, 120);
|
||||
},
|
||||
};
|
||||
|
||||
/** Where my last played set was (its button may be gone once the view arrives), so the pile cards fly from there. */
|
||||
let myPlayRect: DOMRect | null = null;
|
||||
const rememberPlay = (rank: number) => {
|
||||
myPlayRect = document.querySelector(`.dm-group[data-n="${cssEsc(String(rank))}"]`)?.getBoundingClientRect() ?? null;
|
||||
};
|
||||
|
||||
/** Brief dim of a seat (pass). */
|
||||
function dim(el: Element | null): void {
|
||||
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
|
||||
(el as HTMLElement).animate([{ opacity: 1 }, { opacity: 0.4, offset: 0.35 }, { opacity: 1 }], { duration: 650, easing: 'ease-out' });
|
||||
}
|
||||
|
||||
const CSS = `
|
||||
.dm { width: 100%; max-width: 1080px; display: flex; flex-direction: column; gap: 10px; align-self: center; }
|
||||
.dm-tip { display: flex; align-items: center; gap: 8px; background: var(--primary-soft); color: var(--text); border-radius: 12px; padding: 6px 6px 6px 12px; font-weight: 700; font-size: .95rem; }
|
||||
@@ -60,6 +107,7 @@ const CSS = `
|
||||
.dm-seat { position: relative; flex: 0 1 124px; min-width: 104px; background: var(--surface); color: var(--text); border-radius: 12px; padding: 6px 8px;
|
||||
border: 3px solid transparent; box-shadow: var(--shadow); display: flex; flex-direction: column; gap: 2px; font-size: .88rem; animation: dm-in .35s ease both; }
|
||||
.dm-seat.turn { border-color: var(--focus); }
|
||||
.dm-seat.anim-glow { animation: anim-glow 1.4s ease-in-out infinite; }
|
||||
.dm-seat.me { background: var(--primary-soft); }
|
||||
.dm-seat.out { opacity: .7; }
|
||||
.dm-seat .nm { font-weight: 800; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0; }
|
||||
@@ -80,7 +128,6 @@ const CSS = `
|
||||
.dm-prev .dm-card .nm { display: none; }
|
||||
.dm-set { display: flex; }
|
||||
.dm-set > .dm-card + .dm-card { margin-left: calc(var(--w) * -0.55); }
|
||||
.dm-set.top { animation: dm-fly .3s ease-out; }
|
||||
.dm-card { --w: 60px; position: relative; flex: none; width: var(--w); height: calc(var(--w) * 1.4); border-radius: calc(var(--w) * .13); background: #fffdf7; color: #1f2937;
|
||||
border: 2px solid var(--c, #444); box-shadow: 0 2px 4px rgba(0,0,0,.28); display: flex; flex-direction: column; align-items: center; overflow: hidden; font-family: inherit; }
|
||||
.dm-card .band { width: 100%; background: var(--c, #444); color: #fff; font-weight: 900; font-size: calc(var(--w) * .2); line-height: 1.35; text-align: left; padding-left: 4px; }
|
||||
@@ -129,10 +176,9 @@ const CSS = `
|
||||
.dm-flip { animation: dm-flip .7s ease both; }
|
||||
@keyframes dm-in { from { transform: translateY(-8px); opacity: 0; } to { transform: none; opacity: 1; } }
|
||||
@keyframes dm-pop { 0% { transform: scale(.6); } 70% { transform: scale(1.12); } 100% { transform: scale(1); } }
|
||||
@keyframes dm-fly { from { transform: translateY(40px) scale(.85); opacity: .2; } to { transform: none; opacity: 1; } }
|
||||
@keyframes dm-flip { from { transform: rotateY(180deg); } to { transform: none; } }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.dm *, .dm-seat, .dm-set.top, .dm-rev, .dm-bubble, .dm-draw, .dm-flip { animation: none !important; transition: none !important; }
|
||||
.dm *, .dm-seat, .dm-rev, .dm-bubble, .dm-draw, .dm-flip { animation: none !important; transition: none !important; }
|
||||
}
|
||||
@media (max-width: 719px) {
|
||||
.dm { gap: 8px; }
|
||||
@@ -195,7 +241,8 @@ function Seats({ v, players, me, deadline }: { v: DalmutiView; players: Record<s
|
||||
return (
|
||||
<li
|
||||
key={s.id}
|
||||
className={`dm-seat${s.isTurn && v.phase === 'playing' ? ' turn' : ''}${s.id === me ? ' me' : ''}${s.place ? ' out' : ''}`}
|
||||
className={`dm-seat${s.isTurn && v.phase === 'playing' ? ' turn anim-glow' : ''}${s.id === me ? ' me' : ''}${s.place ? ' out' : ''}`}
|
||||
data-fx-seat={s.id}
|
||||
style={{ animationDelay: `${i * 40}ms` }}
|
||||
aria-label={seatLabel(s, v, players, me)}
|
||||
>
|
||||
@@ -251,7 +298,7 @@ function TableArea({ v, players, me }: { v: DalmutiView; players: Record<string,
|
||||
const leaderName = t.leader === me ? '내가' : `${nick(players, t.leader)}님이`;
|
||||
const curName = v.current === me ? '내' : `${nick(players, v.current ?? '')}님`;
|
||||
return (
|
||||
<div className="dm-table" role="region" aria-label="바닥">
|
||||
<div className="dm-table" data-fx="dm-center" role="region" aria-label="바닥">
|
||||
{top ? (
|
||||
<>
|
||||
<div className="dm-now" aria-live="polite">
|
||||
@@ -339,6 +386,7 @@ function PlayHand({ v, act, pending }: { v: DalmutiView; act: (a: unknown) => vo
|
||||
setSel(null);
|
||||
return;
|
||||
}
|
||||
sfx.select();
|
||||
if (top) setSel({ rank: g.n, count: top.count, mix: ch.needsJester });
|
||||
else setSel({ rank: g.n, count: ch.have, mix: false });
|
||||
};
|
||||
@@ -360,6 +408,7 @@ function PlayHand({ v, act, pending }: { v: DalmutiView; act: (a: unknown) => vo
|
||||
};
|
||||
const send = () => {
|
||||
if (!ids || !legal) return;
|
||||
rememberPlay(sel!.rank);
|
||||
act({ type: 'play', cardIds: ids });
|
||||
setSel(null);
|
||||
};
|
||||
@@ -374,7 +423,7 @@ function PlayHand({ v, act, pending }: { v: DalmutiView; act: (a: unknown) => vo
|
||||
</strong>
|
||||
{mine && <span className="small muted">{top ? `${setText(top)}보다 낮은 숫자를 골라요` : '낼 숫자를 골라요'}</span>}
|
||||
</div>
|
||||
<div className="dm-hand" role="group" aria-label="내 카드(숫자별). 좌우 방향키로 고르고 Enter로 선택해요" onKeyDown={(e) => onArrowKeys(e, 'button.dm-group')}>
|
||||
<div className="dm-hand" data-fx="dm-hand" role="group" aria-label="내 카드(숫자별). 좌우 방향키로 고르고 Enter로 선택해요" onKeyDown={(e) => onArrowKeys(e, 'button.dm-group')}>
|
||||
{groups.map((g) => {
|
||||
const c = choice(g.n);
|
||||
const picked = sel?.rank === g.n;
|
||||
@@ -508,7 +557,7 @@ function RevolutionPanel({ v, players, me, act, pending }: { v: DalmutiView; pla
|
||||
const my = v.my;
|
||||
const done = v.seats.filter((s) => s.confirmed).length;
|
||||
return (
|
||||
<div className="dm-panel">
|
||||
<div className="dm-panel" data-fx="dm-center">
|
||||
<h3>
|
||||
{v.round}라운드 준비 · 손패 확인 ({done}/{v.seats.length})
|
||||
</h3>
|
||||
@@ -553,11 +602,12 @@ function TaxPanel({ v, players, me, act, pending }: { v: DalmutiView; players: R
|
||||
const subject = (id: string) => (id === me ? '내가' : `${nick(players, id)}님이`);
|
||||
const toggle = (id: string) => {
|
||||
if (!owe) return;
|
||||
sfx.select();
|
||||
if (picked.includes(id)) setPicked(picked.filter((x) => x !== id));
|
||||
else setPicked(picked.length >= owe.count ? [...picked.slice(1), id] : [...picked, id]);
|
||||
};
|
||||
return (
|
||||
<div className={`dm-panel${owe ? ' hot' : ''}`}>
|
||||
<div className={`dm-panel${owe ? ' hot' : ''}`} data-fx="dm-center">
|
||||
<h3>세금 카드 교환</h3>
|
||||
<RoundRecap v={v} players={players} me={me} />
|
||||
<ul style={{ margin: 0, paddingLeft: 20 }} aria-label="세금 내역">
|
||||
@@ -685,6 +735,8 @@ function DalmutiBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
const mine = isMyTurn(v, me);
|
||||
const prevMine = useRef(false);
|
||||
const lastLog = v.log[v.log.length - 1];
|
||||
const [banner, showBanner] = useBanner();
|
||||
useDalmutiFx(v, me, players, showBanner);
|
||||
useEffect(() => {
|
||||
if (mine && !prevMine.current) {
|
||||
haptic(40);
|
||||
@@ -715,10 +767,101 @@ function DalmutiBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{banner}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const logKey = (e: LogEntry) => `${e.seq}-${e.t}-${'p' in e ? e.p : 'from' in e ? e.from : ''}`;
|
||||
|
||||
/** Sounds + motion for every change of the table, mine or anyone else's (log entries since the last view). */
|
||||
function useDalmutiFx(v: DalmutiView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
|
||||
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, ms) : f());
|
||||
const who = (id: string) => (id === me ? '나' : `${nick(players, id)}님`);
|
||||
// A new round (or the very first deal): cards go from the middle to everyone.
|
||||
const deal = (delay = 0) => {
|
||||
const c = fxEl('dm-center');
|
||||
later(delay, sfx.shuffle);
|
||||
later(delay + 300, () => sfx.deal(6, 60));
|
||||
document.querySelectorAll('.dm-hand .dm-group, .dm-hand .dm-one').forEach((el, i) => flyFrom(el, c, { delay: delay + 280 + i * 45, rotate: 10 }));
|
||||
for (const s of v.seats) if (s.id !== me) flyGhost(c, seatEl(s.id), { count: 3, gap: 90, delay: delay + 280 });
|
||||
};
|
||||
useNewEntries(v.log, logKey, (fresh) => {
|
||||
const lastPlay = [...fresh].reverse().find((e) => e.t === 'play');
|
||||
let t = 0;
|
||||
for (const e of fresh) {
|
||||
const at = t;
|
||||
switch (e.t) {
|
||||
case 'play': {
|
||||
if (e === lastPlay) {
|
||||
const from = e.p === me ? (myPlayRect ?? fxEl('dm-hand')) : seatEl(e.p);
|
||||
document.querySelectorAll('.dm-set.top .dm-card').forEach((el, i) => flyFrom(el, from, { delay: at + i * 60, ms: 340, rotate: -12 }));
|
||||
}
|
||||
if (e.p === me) myPlayRect = null;
|
||||
later(at, () => dmSfx.set(e.count));
|
||||
t += 150;
|
||||
break;
|
||||
}
|
||||
case 'pass':
|
||||
later(at, dmSfx.knock);
|
||||
dim(seatEl(e.p));
|
||||
t += 120;
|
||||
break;
|
||||
case 'trick':
|
||||
// Everyone passed: the pile is swept to whoever leads next.
|
||||
flyGhost(fxEl('dm-center'), seatEl(e.p), { count: 3, gap: 60, delay: at, ms: 420 });
|
||||
later(at, sfx.whoosh);
|
||||
later(at + 380, () => bump(seatEl(e.p)));
|
||||
t += 200;
|
||||
break;
|
||||
case 'out':
|
||||
showBanner(`${e.place}등!`, e.place === 1 ? 'gold' : 'green', e.p === me ? '손패를 다 냈어요' : `${nick(players, e.p)}님`);
|
||||
later(at + 80, e.place === 1 ? sfx.fanfare : sfx.good);
|
||||
bump(seatEl(e.p));
|
||||
t += 250;
|
||||
break;
|
||||
case 'revolution': {
|
||||
const great = e.kind === 'great';
|
||||
showBanner(great ? '대혁명!' : '혁명!', great ? 'dark' : 'red', great ? `${who(e.p)} · 신분이 뒤집혀요` : `${who(e.p)} · 세금 없음`);
|
||||
later(at, () => dmSfx.revolution(great));
|
||||
t += 300;
|
||||
break;
|
||||
}
|
||||
case 'tax':
|
||||
case 'return':
|
||||
flyGhost(seatEl(e.from), seatEl(e.to), { count: e.n, gap: 90, delay: at, ms: 520 });
|
||||
later(at, e.t === 'tax' ? dmSfx.tax : dmSfx.give);
|
||||
t += 350;
|
||||
break;
|
||||
case 'round':
|
||||
// The next round's cards are dealt (not after the last round).
|
||||
if (v.phase !== 'finished') {
|
||||
deal(at + 500);
|
||||
t += 1300;
|
||||
}
|
||||
break;
|
||||
case 'timeout':
|
||||
later(at, sfx.tick);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
const started = useRef(false);
|
||||
useLayoutEffect(() => {
|
||||
if (started.current) return;
|
||||
started.current = true;
|
||||
// Mounted right at the start of the game (nobody has done anything yet): show the deal once.
|
||||
const fresh =
|
||||
v.round === 1 &&
|
||||
(v.phase === 'revolutionCheck'
|
||||
? v.log.length === 0 && !v.seats.some((s) => s.confirmed)
|
||||
: v.phase === 'taxReturn' && !v.options.revolution && v.log.every((e) => e.t === 'tax') && v.taxPending.every((p) => !p.done));
|
||||
if (fresh) deal();
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function rulesLine(o: DalmutiOptions): string {
|
||||
@@ -729,7 +872,7 @@ function rulesLine(o: DalmutiOptions): string {
|
||||
o.jesterTaxable ? '세금에 광대 포함' : '세금에 광대 빼기',
|
||||
o.passLocksOut ? '패스하면 트릭에서 빠짐' : '패스해도 다시 낼 수 있음',
|
||||
o.removeHighCards ? '9~12 빼기' : '',
|
||||
`${o.turnSeconds}초`,
|
||||
o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
@@ -853,7 +996,7 @@ function statusText(v: DalmutiView, me: string | null, players: Record<string, P
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
return (
|
||||
<div className="segmented" role="group" aria-label={label}>
|
||||
{options.map(([k, l]) => (
|
||||
@@ -895,7 +1038,7 @@ function Options({ value: o, onChange }: OptionsProps<DalmutiOptions>) {
|
||||
<Seg label="혁명 규칙" value={o.revolution} options={onOff} onChange={(revolution) => set({ revolution })} />
|
||||
</Field>
|
||||
<Field label="한 턴 제한 시간">
|
||||
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[15, '15초'], [20, '20초'], [30, '30초'], [45, '45초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[15, '15초'], [20, '20초'], [30, '30초'], [45, '45초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||
</Field>
|
||||
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
|
||||
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
|
||||
@@ -926,7 +1069,7 @@ function optionsSummary(o: DalmutiOptions): string {
|
||||
if (o.jesterTaxable) parts.push('세금에 광대');
|
||||
if (o.passLocksOut) parts.push('패스하면 빠짐');
|
||||
if (o.removeHighCards) parts.push('9~12 빼기');
|
||||
parts.push(`${o.turnSeconds}초`);
|
||||
parts.push(o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`);
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
@@ -990,7 +1133,10 @@ function Rules({ options }: { options?: DalmutiOptions }) {
|
||||
라운드에서 1등은 (사람 수 − 1)점, 마지막 순위는 0점을 받아요. {o?.scoring === 'last-round' ? '이 방은 마지막 라운드 순위가 최종 순위예요.' : '총점이 높은 사람이 이기고, 같으면 마지막 라운드 순위로 정해요.'}{' '}
|
||||
점수는 이 방 안에서만 쓰는 표시용이에요.
|
||||
</p>
|
||||
<p>시간 안에 고르지 않으면 새로 시작할 때는 가장 큰 숫자 카드를 모두 내고, 따라 낼 때는 패스해요.</p>
|
||||
<p>
|
||||
{o?.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 고르지 않으면'} 새로 시작할 때는 가장 큰 숫자 카드를 모두 내고, 따라 낼 때는
|
||||
패스해요.
|
||||
</p>
|
||||
<CardTable removeHigh={o?.removeHighCards} />
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
/** 다빈치 코드 화면 (docs/games/davinci-code.md §9). */
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState, type CSSProperties } from 'react';
|
||||
import type { DavinciGuess, DavinciOptions, DavinciTileView, DavinciView, PhaseKind, TColor, TileValue } from '@bg/games/davinci-code';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -20,10 +20,64 @@ const valueKo = (v: TileValue) => (v === 'joker' ? '조커' : String(v));
|
||||
const faceOf = (v: TileValue) => (v === 'joker' ? '−' : String(v));
|
||||
const hiddenLeft = (row: DavinciTileView[]) => row.filter((t) => !t.revealed).length;
|
||||
|
||||
/** Standing number-tile sounds (synthesized; the site volume is applied by feedback.ts). */
|
||||
const snd = {
|
||||
/** A tile taken from the face-down pile. */
|
||||
draw: () => {
|
||||
noise(120, 0.08, 0, 'bandpass', 1200, 0.7);
|
||||
tone(330, 60, 'triangle', 0.07, 100);
|
||||
},
|
||||
/** A tile slotted into a row: a solid "딸깍". */
|
||||
set: (delay = 0) => {
|
||||
noise(30, 0.15, delay, 'bandpass', 2600, 2);
|
||||
tone(950, 38, 'triangle', 0.09, delay);
|
||||
tone(260, 70, 'sine', 0.08, delay + 10);
|
||||
},
|
||||
/** A tile tipped over face up. */
|
||||
flip: (delay = 0) => {
|
||||
noise(45, 0.11, delay, 'highpass', 3000);
|
||||
tone(620, 70, 'triangle', 0.08, delay + 25, { slideTo: 1240 });
|
||||
},
|
||||
/** Somebody guessed my tile right. */
|
||||
ouch: (delay = 0) => tone(520, 200, 'triangle', 0.1, delay, { slideTo: 300 }),
|
||||
/** A joker goes into a row (only when the viewer can see it is a joker). */
|
||||
joker: (delay = 0) => [1568, 2093, 2637].forEach((f, i) => tone(f, 90, 'triangle', 0.05, delay + i * 60)),
|
||||
/** A player is out. */
|
||||
out: (delay = 0) => [523, 440, 349].forEach((f, i) => tone(f, 170, 'triangle', 0.09, delay + i * 130)),
|
||||
};
|
||||
|
||||
/** A value that shows for `ms` and then clears itself (timer cleaned up on unmount). */
|
||||
function useTimed<T>(): [T | null, (v: T, ms: number) => void] {
|
||||
const [val, setVal] = useState<T | null>(null);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
useEffect(() => () => clearTimeout(timer.current), []);
|
||||
const set = useCallback((v: T, ms: number) => {
|
||||
clearTimeout(timer.current);
|
||||
setVal(v);
|
||||
timer.current = setTimeout(() => setVal(null), ms);
|
||||
}, []);
|
||||
return [val, set];
|
||||
}
|
||||
|
||||
/** Wraps a number that bumps (anim-bump) whenever it changes after the first render. */
|
||||
function Bump({ value, children }: { value: number; children: React.ReactNode }) {
|
||||
const prev = useRef(value);
|
||||
const n = useRef(0);
|
||||
if (prev.current !== value) {
|
||||
prev.current = value;
|
||||
n.current += 1;
|
||||
}
|
||||
return (
|
||||
<span key={n.current} className={n.current ? 'dv-bump anim-bump' : 'dv-bump'}>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function totalMsOf(v: DavinciView): number {
|
||||
if (v.phase === 'chooseStart') return 15_000;
|
||||
if ((v.idle[v.current] ?? 0) >= 3) return 5_000;
|
||||
return v.phase === 'guess' ? v.options.turnSeconds * 1000 : 10_000;
|
||||
return v.phase === 'guess' ? (v.options.turnSeconds ?? 30) * 1000 : 10_000;
|
||||
}
|
||||
|
||||
/** Seats starting with the one after `me` (clockwise); spectators see everyone. */
|
||||
@@ -46,6 +100,10 @@ function guessLine(g: DavinciGuess, players: Record<string, PublicUser>): string
|
||||
}
|
||||
|
||||
const CSS = `
|
||||
.dv-bump { display: inline-block; }
|
||||
.dv-banner { position: fixed; z-index: 40; top: 34%; left: 0; right: 0; margin: 0 auto; width: max-content; max-width: 92vw; text-align: center;
|
||||
padding: 12px 26px; border-radius: 18px; font-size: clamp(1.4rem, 5vw, 2.2rem); font-weight: 900;
|
||||
background: linear-gradient(160deg, #42454d, #141519); color: #fff; border: 2px solid #050505; box-shadow: 0 4px 0 rgba(0,0,0,.45), 0 12px 30px rgba(0,0,0,.35); }
|
||||
.dv-board { width: 100%; max-width: 980px; max-height: 100%; overflow: auto; display: flex; flex-direction: column; gap: 12px; padding: 2px; }
|
||||
.dv-opps { display: grid; gap: 10px; }
|
||||
.dv-player { background: var(--surface); border-radius: var(--radius-lg); padding: 10px 12px; box-shadow: var(--shadow); border: 3px solid transparent; }
|
||||
@@ -74,13 +132,16 @@ const CSS = `
|
||||
.dv-tile.secret { outline: 3px dashed var(--primary); outline-offset: 2px; }
|
||||
.dv-tile.sm { --w: 30px; }
|
||||
.dv-tile.lg { --w: 54px; }
|
||||
.dv-tile.hit { animation: dv-flip .5s ease-out, dv-hit 1.2s ease-out; }
|
||||
.dv-tile.miss { animation: dv-flip .5s ease-out, dv-miss 1.2s ease-out; }
|
||||
.dv-tile.new { animation: dv-drop .35s ease-out; }
|
||||
@keyframes dv-flip { 0% { transform: rotateY(90deg); } 100% { transform: rotateY(0); } }
|
||||
.dv-tile.hit { animation: dv-flip .5s ease-out both, dv-hit 1.2s ease-out both; }
|
||||
.dv-tile.miss { animation: dv-flip .5s ease-out both, dv-miss 1.2s ease-out both; animation-delay: var(--anim-delay, 0ms); }
|
||||
.dv-tile.new { animation: dv-drop .38s ease-out both; animation-delay: var(--anim-delay, 0ms); }
|
||||
.dv-tile.shake { animation: anim-shake .45s ease, dv-miss 1.2s ease-out; }
|
||||
.dv-tile.deal { animation: anim-deal .38s cubic-bezier(0.2, 0.8, 0.3, 1.15) both; animation-delay: var(--anim-delay, 0ms); }
|
||||
.dv-tile.reveal { animation: dv-flip .45s ease-out both; animation-delay: var(--anim-delay, 0ms); }
|
||||
@keyframes dv-flip { 0% { transform: perspective(500px) rotateY(90deg); } 60% { transform: perspective(500px) rotateY(-12deg); } 100% { transform: perspective(500px) rotateY(0); } }
|
||||
@keyframes dv-hit { 0%, 60% { box-shadow: 0 0 0 4px #22c55e, 0 0 18px 6px rgba(34,197,94,.7); } 100% { box-shadow: 0 3px 0 rgba(0,0,0,.35); } }
|
||||
@keyframes dv-miss { 0%, 60% { box-shadow: 0 0 0 4px #ef4444, 0 0 18px 6px rgba(239,68,68,.6); } 100% { box-shadow: 0 3px 0 rgba(0,0,0,.35); } }
|
||||
@keyframes dv-drop { 0% { transform: translateY(-14px); opacity: .3; } 100% { transform: translateY(0); opacity: 1; } }
|
||||
@keyframes dv-drop { 0% { transform: translateY(-34px) scale(.85); opacity: .2; } 70% { transform: translateY(3px); opacity: 1; } 100% { transform: translateY(0); } }
|
||||
.dv-pick { background: none; border: 0; padding: 3px; border-radius: 11px; cursor: pointer; color: inherit; }
|
||||
.dv-pick:disabled { cursor: default; }
|
||||
.dv-pick.can { box-shadow: 0 0 0 3px var(--primary); }
|
||||
@@ -136,19 +197,26 @@ const CSS = `
|
||||
.dv-board { max-height: none; overflow: visible; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.dv-tile.hit, .dv-tile.miss, .dv-tile.new { animation: none; }
|
||||
.dv-tile.hit, .dv-tile.miss, .dv-tile.new, .dv-tile.shake, .dv-tile.deal, .dv-tile.reveal { animation: none; }
|
||||
.dv-banner { display: none; }
|
||||
}
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------- tiles
|
||||
|
||||
type Fx = 'hit' | 'miss' | 'new';
|
||||
type FxKind = 'hit' | 'miss' | 'new' | 'shake' | 'deal' | 'reveal';
|
||||
/** One tile's animation: kind, start delay, and a sequence number so the same kind can replay. */
|
||||
interface Fx {
|
||||
k: FxKind;
|
||||
d: number;
|
||||
s: number;
|
||||
}
|
||||
|
||||
function Tile({ color, n, revealed, mine, size, fx }: { color: TColor; n?: TileValue; revealed: boolean; mine?: boolean; size?: 'sm' | 'lg'; fx?: Fx }) {
|
||||
const known = n !== undefined;
|
||||
const cls = ['dv-tile', color, known ? '' : 'back', revealed ? 'open' : '', mine && !revealed ? 'secret' : '', size ?? '', fx ?? ''].filter(Boolean).join(' ');
|
||||
const cls = ['dv-tile', color, known ? '' : 'back', revealed ? 'open' : '', mine && !revealed ? 'secret' : '', size ?? '', fx?.k ?? ''].filter(Boolean).join(' ');
|
||||
return (
|
||||
<span className={cls} aria-hidden>
|
||||
<span key={fx?.s ?? 0} className={cls} aria-hidden style={fx ? ({ '--anim-delay': `${fx.d}ms`, '--from-y': '-60px', '--from-x': '0px' } as CSSProperties) : undefined}>
|
||||
{known ? faceOf(n) : <span className="q">?</span>}
|
||||
</span>
|
||||
);
|
||||
@@ -161,6 +229,8 @@ function tileLabel(t: DavinciTileView, pos: number, mine: boolean): string {
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
const NO_FX = new Map<string, Fx>();
|
||||
|
||||
interface Sel {
|
||||
target: string;
|
||||
index: number;
|
||||
@@ -171,10 +241,12 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
const myTurn = amPlayer && v.current === me && !!v.alive[me!] && v.phase !== 'chooseStart' && v.phase !== 'finished';
|
||||
const [sel, setSel] = useState<Sel | null>(null);
|
||||
const [val, setVal] = useState<TileValue | null>(null);
|
||||
const [fx, setFx] = useState<Map<string, Fx>>(new Map());
|
||||
const [fx, setFx] = useTimed<Map<string, Fx>>();
|
||||
const [pendFx, setPendFx] = useTimed<Fx>();
|
||||
const [banner, setBanner] = useTimed<{ text: string; s: number }>();
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const prevHist = useRef(v.history.length);
|
||||
const prevPlaced = useRef(JSON.stringify(v.lastPlaced));
|
||||
const seq = useRef(0);
|
||||
const snap = useRef<{ hist: number; phase: PhaseKind; pending: boolean; elim: number; picked: number; rows: Record<string, boolean[]> } | null>(null);
|
||||
const prevTurn = useRef(`${v.current}|${v.phase === 'chooseStart'}`);
|
||||
|
||||
const resetKey = `${v.phase}|${v.current}|${v.history.length}`;
|
||||
@@ -183,30 +255,89 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
setVal(null);
|
||||
}, [resetKey]);
|
||||
|
||||
// Effects + screen-reader text for new guesses and newly placed tiles.
|
||||
// Sounds, tile animations and screen-reader text for what anybody did, from view changes only
|
||||
// (the first view after mounting is just recorded, so joining / reconnecting is silent).
|
||||
useEffect(() => {
|
||||
const placedNow = JSON.stringify(v.lastPlaced);
|
||||
const now = {
|
||||
hist: v.history.length,
|
||||
phase: v.phase,
|
||||
pending: !!v.pending,
|
||||
elim: v.eliminationOrder.length,
|
||||
picked: v.picked ? Object.values(v.picked).filter(Boolean).length : 0,
|
||||
rows: Object.fromEntries(v.seats.map((p) => [p, (v.rows[p] ?? []).map((t) => t.revealed)])),
|
||||
};
|
||||
const prev = snap.current;
|
||||
snap.current = now;
|
||||
if (!prev) return;
|
||||
const next = new Map<string, Fx>();
|
||||
if (v.history.length > prevHist.current) {
|
||||
const g = v.history[v.history.length - 1]!;
|
||||
if (g.correct) next.set(`${g.target}:${g.index}`, 'hit');
|
||||
else if (v.lastPlaced && v.lastPlaced.player === g.by && v.lastPlaced.revealed) next.set(`${g.by}:${v.lastPlaced.index}`, 'miss');
|
||||
setAnnounce(
|
||||
`${nick(players, g.by)}님이 ${nick(players, g.target)}님 ${g.index + 1}번째 타일을 ${valueKo(g.said)}(으)로 추리해서 ${g.correct ? '맞혔어요' : '틀렸어요'}.`,
|
||||
);
|
||||
if (g.correct && g.by === me) haptic(30);
|
||||
} else if (placedNow !== prevPlaced.current && v.lastPlaced) {
|
||||
next.set(`${v.lastPlaced.player}:${v.lastPlaced.index}`, v.lastPlaced.revealed ? 'miss' : 'new');
|
||||
const put = (key: string, k: FxKind, d = 0) => next.set(key, { k, d, s: ++seq.current });
|
||||
if (prev.phase === 'chooseStart' && v.phase !== 'chooseStart') {
|
||||
// Start tiles dealt into every row.
|
||||
let k = 0;
|
||||
for (const p of v.seats) (v.rows[p] ?? []).forEach((_, i) => put(`${p}:${i}`, 'deal', Math.min(k++ * 60, 900)));
|
||||
sfx.deal(Math.min(k, 10), 60);
|
||||
} else {
|
||||
if (v.phase === 'chooseStart' && now.picked > prev.picked) sfx.click();
|
||||
if (!prev.pending && v.pending) {
|
||||
snd.draw();
|
||||
setPendFx({ k: 'deal', d: 0, s: ++seq.current }, 700);
|
||||
}
|
||||
let t = 0; // delay of the next sound, so a miss and the tile it costs are heard one after another
|
||||
const g = now.hist === prev.hist + 1 ? v.history[v.history.length - 1]! : null;
|
||||
if (g) {
|
||||
if (g.correct) {
|
||||
put(`${g.target}:${g.index}`, 'hit');
|
||||
snd.flip();
|
||||
if (g.target === me) snd.ouch(140);
|
||||
else sfx.good();
|
||||
if (g.by === me) haptic(30);
|
||||
} else {
|
||||
put(`${g.target}:${g.index}`, 'shake');
|
||||
sfx.bad();
|
||||
t = 320;
|
||||
}
|
||||
setAnnounce(`${nick(players, g.by)}님이 ${nick(players, g.target)}님 ${g.index + 1}번째 타일을 ${valueKo(g.said)}(으)로 추리해서 ${g.correct ? '맞혔어요' : '틀렸어요'}.`);
|
||||
}
|
||||
for (const p of v.seats) {
|
||||
const a = prev.rows[p] ?? [];
|
||||
const b = now.rows[p] ?? [];
|
||||
const lp = v.lastPlaced;
|
||||
if (b.length === a.length + 1 && lp?.player === p) {
|
||||
// A tile slotted into the row (after 멈추기, a miss, a joker, or at the game end).
|
||||
put(`${p}:${lp.index}`, lp.revealed ? 'miss' : 'new', t);
|
||||
if (lp.revealed) snd.flip(t);
|
||||
else snd.set(t);
|
||||
if (v.rows[p]?.[lp.index]?.n === 'joker') snd.joker(t + 90);
|
||||
} else if (b.length === a.length) {
|
||||
// Own tile shown after a miss with an empty pile, or all tiles opened when someone leaves.
|
||||
let opened = 0;
|
||||
b.forEach((r, i) => {
|
||||
if (r && !a[i] && !(g?.correct && g.target === p && g.index === i)) put(`${p}:${i}`, 'miss', t + opened++ * 80);
|
||||
});
|
||||
if (opened) snd.flip(t);
|
||||
}
|
||||
}
|
||||
if (now.elim > prev.elim) {
|
||||
const out = v.eliminationOrder[v.eliminationOrder.length - 1]!;
|
||||
if (!v.left[out]) {
|
||||
setBanner({ text: out === me ? '내 숨은 타일이 다 드러났어요' : `${nick(players, out)}님 탈락!`, s: ++seq.current }, 1700);
|
||||
// The match result sound itself is played by the room page.
|
||||
if (v.phase !== 'finished') snd.out(t + 250);
|
||||
}
|
||||
}
|
||||
if (prev.phase !== 'finished' && v.phase === 'finished') {
|
||||
// Game over: every tile that was still hidden from me is turned over.
|
||||
let k = 0;
|
||||
for (const p of v.seats) {
|
||||
if (p === me) continue;
|
||||
(v.rows[p] ?? []).forEach((r, i) => {
|
||||
if (!r.revealed && !next.has(`${p}:${i}`)) put(`${p}:${i}`, 'reveal', Math.min(400 + k++ * 50, 1000));
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
prevHist.current = v.history.length;
|
||||
prevPlaced.current = placedNow;
|
||||
if (next.size) {
|
||||
setFx(next);
|
||||
const t = setTimeout(() => setFx(new Map()), 1300);
|
||||
return () => clearTimeout(t);
|
||||
}
|
||||
return undefined;
|
||||
}, [v.history.length, JSON.stringify(v.lastPlaced)]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
if (next.size) setFx(next, 1700);
|
||||
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
const key = `${v.current}|${v.phase === 'chooseStart'}`;
|
||||
@@ -222,6 +353,7 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
|
||||
const canGuess = myTurn && v.phase === 'guess' && !pending;
|
||||
const pick = (target: string, index: number) => {
|
||||
sfx.select();
|
||||
if (sel && sel.target === target && sel.index === index) {
|
||||
setSel(null);
|
||||
setVal(null);
|
||||
@@ -236,17 +368,22 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
<style>{CSS}</style>
|
||||
<div className="dv-opps">
|
||||
{opponentsOf(v, me).map((p) => (
|
||||
<PlayerRow key={p} id={p} view={v} me={me} players={players} deadline={deadline} fx={fx} canPick={canGuess && !!v.alive[p]} sel={sel} onPick={pick} />
|
||||
<PlayerRow key={p} id={p} view={v} me={me} players={players} deadline={deadline} fx={fx ?? NO_FX} canPick={canGuess && !!v.alive[p]} sel={sel} onPick={pick} />
|
||||
))}
|
||||
</div>
|
||||
<div className="dv-mid">
|
||||
<Center view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} />
|
||||
<Center view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} pendFx={pendFx} />
|
||||
<ActionPanel view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} sel={sel} val={val} setVal={setVal} onCancel={() => (setSel(null), setVal(null))} />
|
||||
</div>
|
||||
{amPlayer && <MyRow view={v} me={me!} players={players} act={act} pending={pending} myTurn={myTurn} deadline={deadline} fx={fx} />}
|
||||
{amPlayer && <MyRow view={v} me={me!} players={players} act={act} pending={pending} myTurn={myTurn} deadline={deadline} fx={fx ?? NO_FX} />}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{banner && (
|
||||
<div key={banner.s} className="dv-banner anim-banner" aria-hidden>
|
||||
{banner.text}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -271,7 +408,12 @@ function PlayerHead({ id, view: v, me, players, deadline }: { id: string; view:
|
||||
{v.alive[id] && (v.idle[id] ?? 0) >= 3 && <span className="dv-badge">자리 비움</span>}
|
||||
{v.phase === 'chooseStart' && v.alive[id] && <span className={`dv-badge${choosing ? '' : ' ok'}`}>{choosing ? '고르는 중' : '다 골랐어요'}</span>}
|
||||
<span className="small muted" style={{ marginLeft: 'auto' }}>
|
||||
{v.phase !== 'chooseStart' && `숨은 타일 ${hiddenLeft(row)}개 · `}맞힘 {st.correct}/{st.guesses}
|
||||
{v.phase !== 'chooseStart' && (
|
||||
<>
|
||||
숨은 타일 <Bump value={hiddenLeft(row)}>{hiddenLeft(row)}</Bump>개 ·{' '}
|
||||
</>
|
||||
)}
|
||||
맞힘 <Bump value={st.correct}>{st.correct}</Bump>/{st.guesses}
|
||||
</span>
|
||||
{(isTurn || choosing) && <TurnTimer deadline={deadline} totalMs={totalMsOf(v)} mine={id === me} size={30} />}
|
||||
</div>
|
||||
@@ -303,7 +445,7 @@ function PlayerRow({
|
||||
const isTurn = v.phase !== 'finished' && v.phase !== 'chooseStart' && v.current === id;
|
||||
const name = nick(players, id);
|
||||
return (
|
||||
<section className={`dv-player${isTurn ? ' turn' : ''}${v.alive[id] || v.phase === 'finished' ? '' : ' out'}`} aria-label={`${name}님 타일`}>
|
||||
<section className={`dv-player${isTurn ? ' turn anim-glow' : ''}${v.alive[id] || v.phase === 'finished' ? '' : ' out'}`} aria-label={`${name}님 타일`}>
|
||||
<PlayerHead id={id} view={v} me={me} players={players} deadline={deadline} />
|
||||
<div className="dv-row" role="group" aria-label={`${name}님 타일 줄`}>
|
||||
{row.length === 0 && <span className="small muted">{v.phase === 'chooseStart' ? '시작 타일을 기다리는 중이에요' : '타일이 없어요'}</span>}
|
||||
@@ -363,7 +505,7 @@ function MyRow({
|
||||
</button>
|
||||
);
|
||||
return (
|
||||
<section className={`dv-player dv-me${isTurn ? ' turn' : ''}${v.alive[me] || v.phase === 'finished' ? '' : ' out'}`} aria-label="내 타일">
|
||||
<section className={`dv-player dv-me${isTurn ? ' turn anim-glow' : ''}${v.alive[me] || v.phase === 'finished' ? '' : ' out'}`} aria-label="내 타일">
|
||||
<PlayerHead id={me} view={v} me={me} players={players} deadline={deadline} />
|
||||
<div className="dv-row" role="group" aria-label="내 타일 줄">
|
||||
{row.length === 0 && <span className="small muted">{v.phase === 'chooseStart' ? '시작 타일 색을 고르면 여기에 놓여요' : '타일이 없어요'}</span>}
|
||||
@@ -403,7 +545,23 @@ function MyRow({
|
||||
);
|
||||
}
|
||||
|
||||
function Center({ view: v, me, players, act, pending, myTurn }: { view: DavinciView; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; myTurn: boolean }) {
|
||||
function Center({
|
||||
view: v,
|
||||
me,
|
||||
players,
|
||||
act,
|
||||
pending,
|
||||
myTurn,
|
||||
pendFx,
|
||||
}: {
|
||||
view: DavinciView;
|
||||
me: string | null;
|
||||
players: Record<string, PublicUser>;
|
||||
act: (a: unknown) => void;
|
||||
pending: boolean;
|
||||
myTurn: boolean;
|
||||
pendFx: Fx | null;
|
||||
}) {
|
||||
const drawing = myTurn && v.phase === 'draw' && !pending;
|
||||
const total = v.pool.black + v.pool.white;
|
||||
const last = v.history[v.history.length - 1];
|
||||
@@ -434,7 +592,7 @@ function Center({ view: v, me, players, act, pending, myTurn }: { view: DavinciV
|
||||
)}
|
||||
</span>
|
||||
<span>
|
||||
{COLOR_SHORT[c]} {v.pool[c]}개
|
||||
{COLOR_SHORT[c]} <Bump value={v.pool[c]}>{v.pool[c]}</Bump>개
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
@@ -444,13 +602,13 @@ function Center({ view: v, me, players, act, pending, myTurn }: { view: DavinciV
|
||||
<button type="button" className={`dv-pile${drawing ? ' can' : ''}`} disabled={!drawing} aria-label={`타일 가져오기, ${total}개 남음`} onClick={() => act({ type: 'draw' })}>
|
||||
<span>타일 가져오기</span>
|
||||
<span className="small">
|
||||
남은 타일 {total}개 (검정 {v.pool.black} · 흰색 {v.pool.white})
|
||||
남은 타일 <Bump value={total}>{total}</Bump>개 (검정 {v.pool.black} · 흰색 {v.pool.white})
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
{v.pending ? (
|
||||
<div className="dv-pending">
|
||||
<Tile color={v.pending.color} n={v.pending.n} revealed={false} mine={v.current === me} />
|
||||
<Tile color={v.pending.color} n={v.pending.n} revealed={false} mine={v.current === me} fx={pendFx ?? undefined} />
|
||||
<span>
|
||||
{v.current === me ? '내가 가져온 타일' : `${nick(players, v.current)}님이 가져온 타일`}
|
||||
<br />
|
||||
@@ -633,7 +791,10 @@ function NumberPad({
|
||||
className={`${x === 'joker' ? 'joker' : ''}${(v.options.deductionHelper || seen.has(`${tile.color}:${x}`)) && impossible(x) ? ' unlikely' : ''}`}
|
||||
aria-pressed={val === x}
|
||||
aria-label={x === 'joker' ? '조커' : String(x)}
|
||||
onClick={() => setVal(x)}
|
||||
onClick={() => {
|
||||
sfx.click();
|
||||
setVal(x);
|
||||
}}
|
||||
>
|
||||
{x === 'joker' ? '조커 (−)' : x}
|
||||
</button>
|
||||
@@ -864,7 +1025,12 @@ function Options({ value: o, onChange }: OptionsProps<DavinciOptions>) {
|
||||
<Seg label="시작 타일 수" value={o.startTiles} options={[['auto', '자동(2·3명 4개, 4명 3개)'], [3, '3개'], [4, '4개'], [5, '5개']]} onChange={(startTiles) => set({ startTiles })} />
|
||||
</Field>
|
||||
<Field label="추리 제한 시간">
|
||||
<Seg label="추리 제한 시간" value={o.turnSeconds} options={[[20, '20초'], [30, '30초'], [45, '45초'], [60, '60초']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||
<Seg
|
||||
label="추리 제한 시간"
|
||||
value={o.turnSeconds === null ? 'none' : String(o.turnSeconds)}
|
||||
options={[['20', '20초'], ['30', '30초'], ['45', '45초'], ['60', '60초'], ['none', '무제한']]}
|
||||
onChange={(k) => set({ turnSeconds: k === 'none' ? null : (Number(k) as 20 | 30 | 45 | 60) })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="가능한 숫자 후보 표시(초보 도움)">
|
||||
<Seg label="후보 표시" value={o.deductionHelper} options={[[false, '끄기'], [true, '켜기']]} onChange={(deductionHelper) => set({ deductionHelper })} />
|
||||
@@ -894,7 +1060,7 @@ function optionsSummary(o: DavinciOptions): string {
|
||||
o.jokers ? '조커 사용' : '조커 없음',
|
||||
o.startTiles === 'auto' ? '시작 타일 자동' : `시작 타일 ${o.startTiles}개`,
|
||||
o.chooseColors ? '색 골라 가져오기' : '무작위로 가져오기',
|
||||
`추리 ${o.turnSeconds}초`,
|
||||
o.turnSeconds === null ? '시간 무제한' : `추리 ${o.turnSeconds}초`,
|
||||
...(o.tieOrder === 'white-left' ? ['같은 숫자는 흰색 먼저'] : []),
|
||||
...(o.deductionHelper ? ['후보 표시'] : []),
|
||||
].join(' · ');
|
||||
@@ -942,7 +1108,10 @@ function Rules({ options }: { options?: DavinciOptions }) {
|
||||
이미 공개된 같은 색·같은 숫자를 말하는 것처럼 말이 안 되는 추리도 할 수는 있어요(화면에서 알려 줘요). 오른쪽 <strong>추리 기록</strong>에서 누가 어떤 숫자를 말했는지 다시 볼 수 있어요.
|
||||
</p>
|
||||
<p className="muted">
|
||||
시간 안에 추리하지 않으면 공개된 정보로 가장 가능성 있는 작은 숫자를 자동으로 말해요. 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요. 결과 화면에는 각자 맞힌 횟수와 추리 횟수가 나와요.
|
||||
{o?.turnSeconds === null
|
||||
? '시간 제한이 없어서 천천히 생각해도 돼요. 연결이 끊긴 채로 오래 지나면 공개된 정보로 가장 가능성 있는 작은 숫자를 자동으로 말해요.'
|
||||
: '시간 안에 추리하지 않으면 공개된 정보로 가장 가능성 있는 작은 숫자를 자동으로 말해요. 세 번 연속 시간을 넘기면 제한 시간이 5초로 줄어요.'}{' '}
|
||||
결과 화면에는 각자 맞힌 횟수와 추리 횟수가 나와요.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
|
||||