Compare commits

...

156 Commits

Author SHA1 Message Date
EJClaw
c2aaff5762 같은 판 경주: 포기·실패한 사람에게는 다른 사람이 푸는 동안 정답을 보내지 않음(다 풀었거나 게임이 끝났을 때만), 지뢰찾기는 밟은 지뢰만 바로 표시
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 14:40:57 +09:00
EJClaw
9f9d20a641 솔리테어 아이콘을 빨간 하트 이모지로(글자 하트는 검게 보임)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 14:29:59 +09:00
EJClaw
1b9acb9fc1 새 게임 5개(같은 판 경주): 지뢰찾기, 사천성, 솔리테어, 스도쿠, 네모네모 로직
- 공통 틀 race: 같은 시드 판을 모두 각자 동시에, 3초 카운트다운, 제한 시간/무제한, 포기, 다 푼 시간 → 푼 만큼 순위, live 컴퓨터
- 지뢰찾기: 초급·중급·고급, 모두에게 같은 곳이 열린 채 시작, 깃발·한꺼번에 열기, 휴대폰 길게 누르기·깃발 모드
- 사천성: 마작패 72·112·136장, 두 번 이하로 꺾이는 선, 항상 풀리는 배치, 막히면 자동 섞기, 힌트
- 솔리테어: 클론다이크(1장·3장)·프리셀·스파이더(1·2·4무늬), 되돌리기, 자동 정리
- 스도쿠: 답이 하나인 문제 생성기(쉬움·보통·어려움), 메모, 겹침 표시, 힌트
- 네모네모 로직: 그림 37개(5×5·10×10·15×15, 모두 줄 논리만으로 풀림), 드래그 칠하기·X 표시, 풀면 그림과 이름
- 게임 46개, 컴퓨터 상대 42개, 게임 고르기에 혼자·퍼즐 탭
(아발론·모노레일은 아직 공개 전이라 이 배포에서 뺌; 작업 갈래 codex/owner/grp_discord_joke-app 2773f5c..에서 옮김)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 14:29:01 +09:00
EJClaw
35f2310f8d 타자 대결 연습: 한 사람이 나가도 남은 사람은 끝까지 침(대결만 한 명 남으면 끝)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:21:21 +09:00
EJClaw
892f64db0e e2e typingPracticeLong: '다 쳤어요' 글이 상태 줄과 판에 함께 있어 first()
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:13:02 +09:00
EJClaw
943e4be3fd 타자 대결 연습 모드: 한컴 타자연습처럼 짧은글 10문장·단어 20개·긴글 한 편 전체를 제한 시간·점수 없이
- 대결 방식에 "연습" 추가(각자 치기, 라운드 1번, 시계·점수 없음). 긴글은 고른 주제 중 한 편을 처음부터 끝까지(8줄 단락이 아님).
- 줄마다 첫 타부터 시간을 재서 줄 사이에 쉬어도 타수가 안 떨어짐(첫 타 몫 0.15초 앞당김 → 붙여 넣기 막기 그대로).
  줄 최고 타수(best) 기록. 컴퓨터도 연습에서는 첫 타를 바로 보냄.
- 화면: 라운드 대신 걸린 시간, 지금·평균·최고 타수·정확도·진행 %, 끝나면 평균·최고·정확도·틀린 줄, 참가자 옆은 타수.
  설정에서 라운드·제한 시간 숨김, 종목 이름 "연습 종목", 도움말·규칙·요약 카드·docs.
- 테스트: 연습 4개(엔진), 무작위 대국 2가지, 컴퓨터 1가지, 도움말 1개, e2e typingPractice·typingPracticeLong.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:09:37 +09:00
EJClaw
122cf5ed1f 타자 대결: 서바이벌이 반드시 끝나게(모두 동시 탈락·동점 3번 연속이면 남은 사람 공동 1점, 문제 60개 상한), 라운드 끝난 뒤 평균 타수·정확도 중복 합산 고침, 정확도 0%를 100%로 보이던 것 고침
- 남은 사람이 모두 한꺼번에 탈락하게 되어 아무도 안 빠지는 문제(시간별은 모두 동점인 간격)가 SURVIVAL_STALL_LIMIT(3)번
  이어지면 라운드를 끝내고 남은 사람이 함께 1점. 누가 치거나 탈락하면 횟수는 0으로. 함께 치기는 SURVIVAL_MAX_ITEMS(60)번째
  문제에서도 끝. 라운드 요약 "더 탈락하는 사람이 없어서 남은 사람이 함께 1점을 얻어요".
- seatView: 진행 중인 라운드만 누적에 더하고, roundEnd·ended에서는 endRound가 이미 더한 누적만 보여 줌.
- SeatView.roundTried·tried(무언가 제출했는지)로 "아직 없음"(-)과 실제 0%를 구분(화면·도움말).
- 테스트: 네 탈락 조건 모두 아무도 안 칠 때 200번 안에 끝남, 모두 늘 시간 안에 칠 때 60문제에서 끝, 진짜 탈락이 횟수를
  초기화, 라운드 뒤 자리 표시 = 최종 결과, 전부 틀린 답의 정확도 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:53:52 +09:00
EJClaw
fffb860282 새 게임 타자 대결: 한국어·영어, 가장 먼저 입력·서바이벌·타수 비교·정확도 대결·타임어택, 단어·짧은글·긴글, 주제 여러 개, 1~10라운드
- 규칙 packages/games/src/typing: 함께 치기(같은 문제를 동시에, 정해지면 1.5초 쉬고 다음)와 각자 치기(한 줄씩 자기 속도로).
  가장 먼저 입력은 문제마다 먼저 정확하게 친 사람 1점, 나머지는 라운드 1등 1점, 최종은 점수 → 평균 타수 → 정확도.
  서바이벌 탈락 조건: 틀렸을 때(목숨 1~5, 기본 3)·문장별(가장 늦게 친 사람)·시간별(간격마다 가장 적게 친 사람)·시간 초과.
  서바이벌은 문제마다 시간이 0.9배씩 줄어(900타 + 1초 아래로는 안 줄어) 반드시 끝나고, 모두 한꺼번에 탈락하게 되면 아무도 탈락하지 않음.
  제한 시간 자동(글 길이)/10초~5분/무제한, 타임어택 30초~2분, 3초 카운트다운, 라운드 결과 6초.
- 타수: 두벌식 자판 수(겹모음·겹받침 2타), 조합 중 글자는 친 자판까지 맞은 것으로, 정확도 = 1 − 편집 거리/길이.
  붙여 넣기 막기: 화면에서 막고 서버는 2,400타/분 + 0.15초보다 빠른 정답을 거절, 진행 막대도 그 속도 이상 못 앞섬.
- 진행은 stream 액션(progress)이라 서버는 이벤트만 전달(보기 재계산·DB 쓰기 없이 묶어서 저장).
- 글 묶음 37개 주제: 한국어 단어 8(과일·동물·채소·나라·음식·직업·스포츠·사자성어), 짧은글 4(속담·명언·잰말놀이·일상 문장),
  긴글 11(애국가·별 헤는 밤·서시·진달래꽃·산유화·님의 침묵·훈민정음 서문·전래 동화 3), 영어 단어 7·짧은글 4·긴글 7.
  시는 위키문헌 원문과 대조해 현대 맞춤법으로. 일반 자판 글자만(테스트로 확인), 긴 줄은 띄어쓰기에서 나눔.
- 컴퓨터(live): 레벨에 따라 120~620타(영어 100~500), 읽는 시간, 오타 확률. 함께 치기는 틀리면 고쳐서 다시.
- 화면: 글자별 초록/빨강/조합 중 표시, 긴글은 단락 전체와 지금 줄(자동 스크롤), 다음 두 줄 미리 보기, 한글 조합 중 Enter 처리,
  한/영 경고, 지금 타수·정확도, 모두의 진행 막대(실시간)·목숨 하트, "먼저 쳤어요"/"탈락" 띠, 라운드 결과 표, 소리, 휴대폰.
- 등록: GAMES·LIVE_BOT_STRATEGIES·BOT_GAMES·CATALOG·GAME_UI·아이콘 ⌨️·파티 탭, README(43개), docs/games/typing.md.
- 테스트: 규칙 34·타수/글 묶음 9·컴퓨터 12·방 통합 4·웹 도움말 3, e2e games.e2e.ts typing·typingSpeed·typingSurvival.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:45:19 +09:00
EJClaw
f793391b79 제한 시간 보정 2: 같은 마감 안에서는 투표로 답할 사람이 줄어도 준 시간 유지, 마감은 남은 답할 사람 중 가장 늦은 화면 기준, 자체 시계를 쓰는 게임도 늘어난 마감을 표시
- room: reveal 단계 키를 게임 마감만으로, clockExtra = max(본인, 답할 사람들)
- 라이어·마피아·아발론 시계, 뱅 반응·차례 타이머, 바둑 계가·마작 울기 타이머가 방 마감(연출 시간 포함)을 따름
- 아발론 암살 마감: 당겨진 마감은 숨기고 늘어난 마감은 보여 줌(무제한이면 그대로 숨김)
- 테스트: 공통 재투표(대표자 A·느린 B·A 투표 후 유지), e2e 라이어 화면 시계 = 방 마감

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:26:25 +09:00
EJClaw
bc8cb7ae8c 제한 시간 보정: 같은 단계의 채팅은 준 시간을 유지, 대표자 마감은 실제 답할 사람 기준, 바뀐 마감은 항상 화면에 전달; 이의있음! 재선택 창은 같은 후보여도 이의있음! 화면 뒤에
- room: reveal을 단계(마감·답할 사람·시간 재는 사람)가 바뀔 때만 새로 시작, clockExtra(대표자는 답할 사람들 중 가장 늦은 화면 기준),
  마지막으로 보낸 마감(sentDeadline)과 비교해 deadline 메시지
- 증강 윷놀이 AugSelect: 고를 때마다 새 키(같은 후보 재추첨도 새 창), 열림 조건에 !blocked, 고르는 중(pending)엔 자동으로 안 열림
- 테스트: 오목 마감 연장 전달, 라이어식 공통 단계(대표자 A·답할 사람 B·채팅), e2e 같은 후보 재선택·화면 타이머 = 서버 마감
- e2e 매지컬 애슬릿: 주사위·이동을 다 보여 준 뒤 다음 선택이 나와 한 판이 길어져 시간 한도 420초 → 900초

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:26:22 +09:00
EJClaw
fa53175f51 결과는 움직임이 끝날 때까지(시간 상한 없음), 제한 시간은 각자 화면이 연출을 다 보여 준 뒤부터
- lib/motion: useMotionSettled에서 12초 상한을 없앰(명시한 maxMs만)
- 서버: 클라이언트 settled(seq)를 받으면 그 사람의 제한 시간을 연출에 걸린 만큼 늦춤(보고 전에는 최대 15초×속도,
  보고한 적 없는 화면·컴퓨터·실시간 게임은 예전 그대로), 마감이 바뀌면 deadline 메시지
- 바퀴벌레 포커: 게임을 끝낸 판정은 패배 배너까지 다 끝난 뒤에 끝 화면
- 증강 윷놀이: 선택 창 열림을 후보 묶음마다 따로, 이의있음! 재선택 창은 이의있음! 화면이 사라진 뒤에
- e2e/motion.e2e.ts: 30초 움직임·바퀴벌레 포커 마지막 판정·이의있음! 재선택·다빈치 ×1/8 회귀 확인, 방 타이머 단위 테스트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:26:22 +09:00
EJClaw
4e0eb4d52c 모든 게임: 결과·팝업은 애니메이션이 끝난 뒤에, 증강 윷놀이: 이의있음!이 다음 판에도 뜨게, 증강 고르는 목록·나오게 할 증강을 팝업 목록으로
- lib/motion: motionBusy / useMotionHold / useMotionSettled / useAfterMotionValue / AfterMotion
- 방 화면: 결과 창과 상태 줄은 판이 멈춘 뒤에(실시간 게임은 상태 줄 그대로), 새 판마다 판 화면을 새로 그림
  (결과 창에 둔 채 다음 판이 시작되면 이전 판의 효과 번호가 남아 이의있음!·알림이 안 뜨던 문제)
- 41개 게임: 결과 패널·배너·점수·팝업이 마지막 움직임 뒤에 나오도록 게임별로 정리
- 증강 윷놀이: 명탐정·배달·손버릇·따라쟁이·착각 대상은 아이콘과 설명이 다 보이는 목록에서,
  방 설정의 나오게 할 증강은 팝업 목록에서 스위치로 켜고 끔
- e2e: 늦게 바뀌는 상태 줄·결과 창과 새 증강 화면에 맞춤

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:26:22 +09:00
EJClaw
f18909c44f 문서: 엔진 정의의 publicDeadline 설명
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:26:17 +09:00
EJClaw
72f4f06e21 엔진: 화면에 보낼 마감(publicDeadline)을 방 안 시간 초과와 분리 (아발론 제외 부분)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:26:17 +09:00
EJClaw
0cbda8f551 증강 윷놀이: 모 아니면 도 증강에도 낙 규칙 적용(낙 확률·낙 처리 방식 그대로), 증강 설명에 안내 추가
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 02:40:55 +09:00
EJClaw
c2ce1979b2 증강 윷놀이: 이의있음! 재선택에서는 혼돈 모드 두 번째 후보에도 이의있음!이 안 나오게, 증강 팝업이 위아래 공간이 모자라도 화면 안에 들어오게
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 02:33:09 +09:00
EJClaw
7084a20e59 윷놀이: 모서리 이름을 숫자로(1번 출발 → 2번 → 3번 → 4번), 칸 이름도 'N번 다음 k칸'·'N번 지름길 k칸'으로 쉽게
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 02:33:09 +09:00
EJClaw
0e8ba529c0 증강 윷놀이: 이의있음! 화면 배경을 조금 더 어둡게
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 02:33:09 +09:00
EJClaw
2403b6747f 증강 윷놀이: 이의있음!은 모두 고른 뒤 화면 전체에 크게 띄우고, 그 선택에서 모두가 고른 증강을 없앤 채 모두 새 후보로 다시 고름
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 02:33:09 +09:00
EJClaw
f4fb796dfe 증강 윷놀이: 증강 칩·증강 쓰기 버튼의 설명을 브라우저 title 대신 팝업 카드로(마우스 올리기·키보드 포커스, 휴대폰은 눌러서)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 02:33:08 +09:00
EJClaw
f9ed734db4 증강 윷놀이: 얼음!·뒤로 돌아·자리 바꾸기가 같은 칸의 상대 말뭉치 중 고른 하나만 대상으로 함 (targetPiece)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 08:28:46 +09:00
EJClaw
daac1982fa 증강 윷놀이: 증강 아이콘 101개, 사이트 추가 증강 20개 더(모두 30개), 추가 증강 기본 꺼짐
- 증강마다 48×48 SVG 아이콘(aug-icons/): 타일 색 = 종류(규칙·즉시·사용·승리 조건), 그림 = 증강.
  선택 카드·사람 카드 칩·쓰기 버튼·승리 팝업·방 설정 목록·규칙 보기에 표시. 고양이가 된 증강은 회색 고양이.
  모아 보기: apps/web/scripts/aug-icon-sheet.tsx
- 새 증강 20개: 다시 던지기, 곱빼기, 올인, 저주 인형, 얼음!, 자석, 뒤로 돌아, 꼴찌의 반란, 텃세, 따라쟁이,
  청개구리, 사냥꾼, 줍줍, 도장 깨기, 스타트 대시, 방공호, 벼락, 블랙홀, 로켓 발사, 최후의 일격 (규칙·컴퓨터·테스트·문서)
- augOff 기본값 = 이 사이트 추가 증강 30개(방에서 [추가 증강 켜기]로 켬)
- 카니발리즘: 내 말 잡기를 '잡기'로 세지 않음(ownCaptures) → 개돼지와 함께일 때 컴퓨터·시간 초과가
  자기 말을 잡고 다시 던지기를 끝없이 반복하던 문제 수정
- 방 설정 탭이 방 정보 갱신으로 다시 그려질 때 [윷놀이 설정]으로 되돌아가던 문제 수정

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 08:17:47 +09:00
EJClaw
5666b227e7 증강 윷놀이: 방 설정의 [기본 설정] 탭 이름을 [윷놀이 설정]으로 변경 (일반 윷놀이 설정으로 헷갈리지 않게)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 02:01:42 +09:00
EJClaw
9ba93e9576 증강 윷놀이: 거머리·네크로맨서 연결도 그 증강이 고양이인 동안 멈춤(승리·탈락·기권 전파), 풀리면 다시 작동
- activeLink: 연결을 만든 증강이 살아 있을 때만 전파(win, eliminate, 기권)
- 사람 카드에 멈춘 연결은 "(멈춤)" 표시
- 회귀 테스트 4개(멈춤, 만료 후 복원, 사슬 중간에서 끊김, 네크로맨서)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 23:00:17 +09:00
EJClaw
049d910dc6 증강 윷놀이: 안개 속 대상 숨기기, 거머리 연쇄 승리, 고양이가 된 증강의 효과(과유불급 가락·특수 말) 멈춤
- 안개: 숨은 말 때문에 생기는 자리 바꾸기·바둑 대상과 포 이동은 화면에서 뺌(서버는 그대로 받음)
- 거머리·네크로맨서 연결이 여러 단계여도 끝까지 같은 순위(고리 연결도 멈춤)
- 윷가락 수는 과유불급이 살아 있을 때만 +2(손버릇으로 옮겨도 따라감), 선봉장·도깨비·포·폰 능력도 고양이일 때는 멈춤
- 회귀 테스트 5개

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 22:54:25 +09:00
EJClaw
28ef4ed947 윷놀이: 증강 윷놀이 옵션 추가 (원작 증강 71개 + 추가 10개, 증강 탭·선택 창·능력·알까기·특수 승리)
- 엔진 aug.ts: 라운드·동시 비공개 증강 선택(1·6·12 등, 혼돈 모드, 후보 수, 제외 목록), 질문(거머리·접기·돌림판·투표·색 맞히기 등),
  특수 말·보호막·함께 서기·함정/선물/똥/마늘/조준/지뢰, 특수 승리·탈락·순위, 컴퓨터(aug-bot.ts), 알까기 물리(physics.ts)
- 화면: 방 설정 [게임 종류] + [증강 윷놀이] 탭(켜기/끄기·찾기), 증강 선택 창, 내 증강 쓰기, 증강 칸, 특수 승리 팝업, 안개, 알까기 조준
- 문서 docs/games/yut-augmented.md, 테스트 aug.test.ts 59개, e2e yut-aug

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 22:42:52 +09:00
EJClaw
d40ba1e121 3장 섯다: 공개패는 항상 맨 왼쪽, 고른 2장은 쇼다운 전까지 다른 사람 화면에 드러나지 않게
- 공개패를 내 패·다른 사람 자리·쇼다운 모든 화면에서 맨 왼쪽에 둠(openFirst)
- 고른 뒤에도 다른 사람 화면은 고르기 전과 같음(공개패 앞면 + 뒷면 2장). 예전엔 남긴 2장만 보여 공개패를 남겼는지/버렸는지 드러났음
- 테스트: 공개패 남김/버림 두 경우 다른 사람 화면이 같음, 쇼다운 공개패 왼쪽, E2E에서 오른쪽 패를 공개하면 왼쪽으로 이동

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 08:07:45 +09:00
EJClaw
1bd69200fd 라이어 게임: 관리자 화면에서 주제·제시어 추가/수정/삭제, 바보 모드 라이어는 비슷한 단어(같은 묶음)
- 제시어 1,519개를 주제별 '비슷한 단어 묶음' 391개로 정리(bank/*.ts groups). 바보 모드 라이어는 제시어와 같은 묶음의 다른 단어를 받음
- 관리자 → 라이어 제시어(/admin/liar): 주제 추가·이름 변경·삭제(내장 주제는 다시 살리기/처음 값으로), 제시어·묶음·다른 표기·컴퓨터 설명 편집, 저장 시 topicProblems 검사
- 저장: liar_topics(바뀐 주제), liar_bank_versions(판본). 새 판 옵션에 bank 판본을 붙여(prepareOptions) 다시 보기·복구가 같은 은행 사용
- 판 상태에 주제 이름·단어 목록·다른 표기를 복사해 진행 중 판은 관리자 수정의 영향을 받지 않음
- 대기실 주제 목록은 GET /api/liar/topics, 관리자 API /api/admin/liar/topics, 기록 liar.topic.*
- 테스트: 엔진(묶음·바보 모드·판본·검사), 서버(관리자 API·새 판·재시작), E2E(관리자 편집 → 대기실 새 주제)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 04:16:17 +09:00
EJClaw
5a878ba991 라이어 게임: 유명 인물 주제를 가수·방송인·배우 65명으로 교체(역사 인물·과학자·운동선수 제외)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 03:32:57 +09:00
EJClaw
17df65bccf 라이어 게임: 주제 7개 추가(게임·영화·유명 인물·브랜드·캐릭터·악기·랜드마크), 제시어 1,089개 → 1,518개
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 02:49:10 +09:00
EJClaw
19fd1fabf2 라이어 게임 문서: 제시어 총수 1,089개로 정정
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 02:34:12 +09:00
EJClaw
fdf54bd554 라이어 게임: 주제 16개(채소·바다 생물·간식·옷·몸·자연·날씨 추가), 제시어 161개 → 1,149개
- 주제마다 bank/<주제>.ts 파일로 나눔, 주제당 단어 55~88개, 단어마다 설명 5개
- 테스트: 주제 16개 이상 × 단어 50개 이상, 한 주제 안에서 단어끼리 포함 관계 없음
- 고르기 모드 단어 목록이 길어져서 목록 칸을 스크롤되게(max-height)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 02:30:25 +09:00
EJClaw
9f16bf833a 라이어 게임 입력 중: 설명 차례인 사람이 토론 채팅을 쳐도 "입력 중"이 보이게
- BotActivity hide → hideBots: 컴퓨터 활동에만 적용(사람의 입력 중은 언제나 채팅 칸에서 오므로 숨기지 않음)
- BotActivity.test.tsx: 설명 차례인 사람의 채팅 입력은 보이고, 설명 차례인 컴퓨터의 입력은 숨겨지고, 상태 줄에는 생각 중만
- e2e: 설명 첫 차례에 말하는 사람이 토론 채팅을 치면 다른 사람 채팅 칸에 입력 중, 보낸 말은 설명으로 치지 않음
- apps/web tsconfig: *.test.tsx도 타입 검사에서 제외(.test.ts와 같게)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 01:33:56 +09:00
EJClaw
03e0e8ed84 라이어 게임: "입력 중…" 표시를 오른쪽 상태 줄에서 토론 채팅 칸 안(입력칸 바로 위)으로
- GameUI.typingInChat: 게임 채팅 칸이 입력 중 표시를 맡고, 상태 줄은 컴퓨터 "생각 중"만 보인다
- BotActivity: only='thinking', hide(설명 차례인 컴퓨터는 채팅이 아니라 설명을 치는 중이라 빼기)
- e2e: 토론 중 입력하면 다른 사람 화면의 토론 채팅 칸 안에만 "입력 중"이 보이는지 확인

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 01:25:13 +09:00
EJClaw
fcc79f05bc 라이어 게임: 토론 채팅을 게임 내내 열기, 설명은 별도 describe 액션으로
- chat은 확인 시간·설명 중(말하는 사람 포함)·토론·투표·정답 맞히기 내내 모두 쓸 수 있다
- 설명은 새 describe 액션(차례인 사람만, 80자). 채팅에 쓴 말은 설명으로 치지 않는다
- 자기 제시어 금지·고운 말 검사는 설명과 채팅 모두 그대로
- 컴퓨터 설명도 describe로 보내고, 모델이 켜져 있으면 "입력 중…" 뒤에 보낸다
- 화면: 채팅 입력칸을 항상 보이게, 설명 차례인 사람에게는 채팅 칸 안내 문구
- 문서(docs/games/liar.md)와 테스트 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 01:20:38 +09:00
EJClaw
e9bc366305 전체 소리 2배: 음량 50이 예전 100 크기로 나오도록 마스터 게인을 음량×2로
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 00:11:01 +09:00
EJClaw
ca8baf5cc8 모든 게임이 남는 화면 전체를 쓰도록: 게임별 폭 상한 제거, 판·카드·말을 --play-w/--play-h에 맞춰 키움
- 카드 게임: 펠트가 남는 높이를 채우고 손패·가운데 더미·자리 크기가 화면에 따라 커짐
- 판 게임: 체스·바둑·오목 등은 높이를 다 쓰고, 장기·쿼리도·젬블로는 넓은 화면에서 조작판을 판 옆으로
- 섯다: 자리를 판 크기에 맞춘 타원 위에 고르게 두고, 많을 때 자리 크기를 줄여 8명에서도 겹치지 않게
- 바퀴벌레 포커 6명·야단법석 달리기 5명 선수 뽑기가 PC에서 넘치지 않게
- 휴대폰·태블릿(1100px 아래) 배치는 그대로
- layout-survey: 컴퓨터 넣기 버튼 기다림, 넘친 높이(px) 표시

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 16:17:15 +09:00
EJClaw
adc3b5337a 게임 화면 공통 틀: 1600px 상한 없애고 창 폭 전체 사용, 판 크기 변수(--play-w/--play-h), 화면 채움 측정 스크립트
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 15:01:46 +09:00
EJClaw
0335a09eef 블랙잭: 카드 연출이 끝나기 전 [다음 판] 막기, 자리 폭 나누기와 카드 크기 맞추기로 겹침·잘림 없애기
- [다음 판]은 딜러 카드가 다 놓여 결과가 보인 뒤에만 눌림(혼자 하는 판도 결과를 건너뛰지 않음)
- 자리마다 테이블 폭을 무게(내 자리·스플릿 자리 더 넓게)로 나누고, 그 폭과 딜러 아래 높이에 맞춰 카드 크기 계산(최소 26px), 손패 3개 이상이면 두 줄
- 좁은 자리는 아바타 없이 이름만, 손패 정보 줄바꿈
- 엔진 테스트: 처음 나눠 주기·딜러 차례 연출 시간이 제한 시간에 더해지는지(1인 판)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 01:43:31 +09:00
EJClaw
02c2a8508c 블랙잭 화면 다시 만듦: 모든 조작을 가운데 판에, 큰 반원 테이블, 숫자·휠·칩 버튼 베팅, 카드 한 장씩 애니메이션
- board.tsx: 판 폭(최대 1180px) 반원 테이블(딜러·카드 슈·인쇄 문구·앞쪽 호의 자리, 내 자리는 가운데 앞 크게)
- 아래 조작판: 내 칩·시간 / 베팅(숫자 입력·Enter, −/+, 마우스 휠·↑↓(Shift 10배), 칩 버튼, 최소·절반·최대·지난 베팅, 막대) / 히트 H·스탠드 S·더블 D·스플릿 P·서렌더 R / 인슈어런스 / 결과·다음 판
- 옆 패널은 칩 순위와 놀이용 칩 안내만
- 카드는 나눠 주는 순서대로 450ms 간격으로 슈에서 날아오고 딜러 홀 카드는 뒤집힘, 합·결과는 카드가 놓인 뒤에
- 엔진: 처음 나눠 주기·딜러 차례에 장당 450ms를 다음 제한 시간에 더함(animLagMs)
- PlayingCard width 속성, 도움말·문서·e2e 스크린샷

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 01:29:31 +09:00
EJClaw
c10fac8e82 3장 섯다를 한게임처럼: 1구 선 하프·다이(1구 체크 없음), 예상족보, 패쪼기
- 엔진: 한게임 흐름(공개패 켬·마지막에 고르기)의 1구 첫 베팅(선)은 하프·다이만, 1구에는 체크 없음(시간 초과는 다이)
- view.myReach: 다음 패로 만들 수 있는 족보(공개 정보만: 덱 구성 − 내 패 − 공개패)
- 족보판 [예상족보 켬/끔]: 못 만드는 족보는 흐리게
- 패쪼기: 새로 받은 패는 뒷면, 밀어 올리면 아래부터 보이고 누르면 바로 뒤집힘, 6초 뒤 자동. 뒤집기 전에는 족보·조합을 숨김
- 도움말·규칙 화면·문서, 엔진 테스트 4개, e2e(1구 하프→콜, 패쪼기 드래그) 맞춤

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 01:16:04 +09:00
EJClaw
9ec756bf38 섯다 화면 꾸밈을 사이트 디자인으로: 흰 카드 자리·아래 판, 담요 무늬 펠트, 낙관(도장) 족보 이름, 파란 '내 차례' 띠, 다크 모드
- 사이트 공용 색 변수(--felt/--wood/--surface/--primary)를 써서 다크 모드에서도 맞음
- 족보판은 사이트 칩 모양, 내 족보 칸은 파란 강조
- 베팅 버튼은 흰 버튼, 누를 수 있을 때만 행동 색 테두리와 숫자 키 배지
- font 단축 속성에 inherit를 넣어 무효가 되던 글꼴(족보 칩·조합·키 배지)을 고침

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 01:03:22 +09:00
EJClaw
81b257df74 섯다: 3장 섯다 방의 재경기(구사·멍텅구리구사·같은 족보)는 2장 섯다로(2장 한 번에, 공개패 없이 베팅 1번)
hand.three를 (재)경기마다 두고 view.threeCard로 알림. 값이 없는 예전 상태는 방의 cardMode를 따름.
컴퓨터 판단·도움말·규칙 화면·문서도 맞춤, 엔진 테스트 2개 추가.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:58:50 +09:00
EJClaw
3125008895 섯다 화면을 한게임 섯다 사진대로 다시 배치: 테이블 아래 금색 판에 족보판·내 얼굴·내 패와 족보·베팅 버튼
- 테이블에는 다른 사람 자리만(패 위, 이름·돈 아래). 내 자리는 테이블 아래 금색 판으로 옮김
- 족보판(jokbo.tsx): 3열 목록, 내 족보 칸 강조, 누르면 그림 2장과 설명. 옆 패널의 족보 도우미는 뺌(전체 표는 규칙 화면)
- 내 패 밑에 지금 족보, 3장이면 세 조합의 족보(가장 센 것 금색)
- 베팅 버튼 두 줄: 콜7·삥4·따당1·하프0 / 다이8·체크5(쿼터2·풀9는 빈칸)
- 3장 섯다 공개패·쓸 패 고르기는 내 패를 직접 누르고, 버튼 자리에 확인 버튼. 카드 공개 묻기, 판 결과와 다음 판으로도 그 자리
- HwatuCard disabled: 고르기 단계가 바뀔 때 카드가 다시 마운트되어 나눠 주기 애니메이션이 반복되던 것을 막음

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:52:24 +09:00
EJClaw
8e549a72c3 섯다: 화투 월 숫자를 왼쪽 아래에 크게(흰 글씨 + 검은 테두리) 표시, 겹친 상대 카드에서도 보이게
HwatuCard에 monthStyle='corner' 추가(기본 'badge'는 고스톱 등 그대로). 상대 자리 카드는 다음 카드가
오른쪽 30%를 덮어 오른쪽 위 배지가 가려졌는데, 왼쪽 아래 숫자는 겹쳐도 보인다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:33:34 +09:00
EJClaw
a81f73ef6d 사건 파일: 새 사건 10개(후보 30개 중 점수로 고름)로 사건 13개, 방 설정은 난이도별 고르기 상자 + 한 줄 소개
- 후보 30개와 점수표·고른 까닭(docs/games/case-file-candidates.md), 사건 쓰는 법(case-file-writing-guide.md).
  예스노 탐정·퀴즈 사립탐정·바다거북 수프에서 이상한 첫 장면, 퀴즈 한 방, 관점 바꾸기, 억지 금지(결정적 단서 두 겹)를 빌림
- 새 사건 c4~c13: 사진 속 그 문 앞 / 장날이 아닌 날 / 반짝이는 것만 사라진 집 (쉬움), 여름밤의 오리온 / 돌아온 두부 /
  웬지 익숙한 시 / 건반 하나가 빠진 녹턴 (보통), 눈 그친 뒤의 발자국 / 틀린 답을 맞힌 우승자 / 시계방에서 사라진 7분 (어려움)
- 사건마다 checks/<id>.ts(빠듯한 길·점검표)와 데이터에서 만든 설계 문서(case-file-cases/<id>.md, bun scripts/case-file-doc.ts).
  cases.test.ts가 새 사건 기준·빠듯한 길·문서 일치를 검사
- 정답 모르는 검토자 풀이(빠듯한 길만 / 전체)로 모순·다른 답·이른 노출을 찾아 고침
- CASE_IDS 13개, random은 13개 중 하나, 사건별 무작위 판 테스트, e2e에서 사건 고르기 상자 확인

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:29:09 +09:00
EJClaw
f1f1104abd 버건디의 성 방패 9·2를 2019 규칙서 15쪽대로 고침, 추정·사이트가 정한 값을 규칙 화면에 표시
- 방패 9: 상품을 팔면 종류당 은화 1개 '대신' 장수만큼(전에는 기본 1개에 장수를 더해 3장에 4개, 수도원 3번이면 5개). 같은 효과면 방패가 수도원보다 우선이라 수도원 3번이 있어도 3장 = 3개
- 방패 2: 남이 일꾼을 얻는 모든 경로(일꾼 받기·하숙집·수도원 2·4번·일꾼 사기)에서 1개. 전에는 일꾼 받기만. gainWorkers 하나로 모음(방패로 받은 일꾼은 다시 퍼지지 않음)
- 회귀 테스트 2개(예전 코드에서 실패 확인), data.ts·설계 문서 방패 설명 고침
- 규칙 화면에 '원작과 다를 수 있는 부분': 핫스트릭(카드 구성·일부 티켓 값·꺾는 쪽 추정 등), 버건디의 성(가축·검은 수도원·수도원 16~23·2·3명 보급소 칸 추정), 젬블로(뒤집기 허용·판 구역·동점)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 00:39:47 +09:00
EJClaw
e34745fe50 문서: 게임 40종(README 표·컴퓨터 상대 수), 로드맵에 새 게임 6개 절, 결정 사항에 6개 게임의 기본값·설정 표
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 00:25:01 +09:00
EJClaw
ce6f662a86 e2e/games.e2e.ts: 새 게임 6개 시나리오를 합칠 때 겹친 자리(도우미 함수 끝·PLANS 끝)에서 블록이 서로 끊겨 파일이 문법 오류였던 것을, 각 브랜치가 더한 줄을 원래 위치에 차례대로 끼워 다시 만듦(타입 검사는 e2e를 보지 않아 놓쳤음)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 00:24:12 +09:00
EJClaw
3769b20ac3 Merge branch 'wip/game-castles-of-burgundy' into codex/owner/grp_discord_joke-app
# Conflicts:
#	apps/web/src/games/help.test.ts
#	apps/web/src/games/registry.ts
#	apps/web/src/lib/catalog-ui.ts
#	docs/games/README.md
#	e2e/games.e2e.ts
#	packages/games/package.json
#	packages/games/src/bots/index.ts
#	packages/games/src/index.ts
#	packages/shared/src/bots.ts
#	packages/shared/src/catalog.ts
2026-10-16 00:13:37 +09:00
EJClaw
c9f4b782e8 새 게임 버건디의 성: 주사위 두 개로 육각 타일을 가져와 1번 공국을 채우는 2~4명 개인전 + 혼자 하기(2019년판 규칙), 시작 성 고르기·2011 수도원·추가 타일·여관·방패를 방 설정으로
- 데이터 packages/games/src/castles-of-burgundy/data.ts: 1번 공국 37칸(구역 13개 계산), 인원별 보급소 칸 색(3인 6번 보급소 B·D 광산), 타일 164장 + 추가 4장 + 여관 5장, 수도원 26+2종, 방패 18종, 점수표. 확인 안 된 데이터(가축 분포·검은 뒷면 수도원·장인 번호·2/3인 칸)는 UNCONFIRMED 주석으로 한 곳에
- 엔진(engine·moves·index): 페이즈 5 × 라운드 5, 일꾼 눈 바꾸기(6↔1, 수도원 8·9~12·방패 16), 가져오기·놓기·팔기·일꾼, 구역 완성·색 보너스·가축·건물 8종·배·성 연쇄를 pending 스택으로, 검은 보급소 구매(수도원 6번 2019/2011), 페이즈 끝 광산·방패 유지비·방패 14/15, 게임 끝 점수와 동점(빈칸 많은 사람 → 차례 트랙 뒤), 혼자 하기(강으로만 넓히기·목표 표시기·상품 5장 바꾸기·색 완성 보상), 시간 초과 자동 진행·자리 비움·기권
- 합법성은 actionError 하나, 합법 수는 후보를 그것으로 거름. view는 더미·다음 페이즈 상품·남의 판 상품 종류를 숨김
- 컴퓨터(bot.ts): 뷰를 상태로 되돌려 자기 차례를 미리 두고 주사위 A → B 묶음을 평가(1~20 한 수+잡음, 21~40 상위 3개, 41~60 상위 6개), 묶음은 차례 끝까지 기억. 한 수 평균 2~18ms
- 화면 apps/web/src/games/castles-of-burgundy/: PC는 가운데 판(보급소 1~6·검은 보급소·여관·남은 상품·색 보너스) + 내 공국 SVG + 오른쪽에 다른 사람 요약·작은 공국, 휴대폰은 [내 공국]/[보급소]/[다른 사람] 탭 + 아래 고정 주사위 줄. 주사위를 고르면 가져올 타일·놓을 칸·팔 상품이 빛나고 "일꾼 n" 배지, 버릴 칸·확인·내는 방법 시트, 성 보너스·배·건물·방패 등 대기 효과는 배너와 버튼. 소리·배너(구역 완성·색 완성·페이즈), 도움말·30초 요약·타일 효과 표
- 등록: GAMES·BOT_STRATEGIES·BOT_GAMES·CATALOG·GAME_UI·GAME_ICON·판·주사위 탭, docs/games/README.md, docs/games/castles-of-burgundy.md(§2 나중에 표시, §13 구현 결정)
- 나중에(데이터 필요): 팀전, 공국 2~10번(duchy), 흰 성, 무역로, 국경 초소
- 테스트: 규칙 48개(문서 §10), 무작위 대국 4가지 옵션(타일·상품 수 보존, JSON 왕복, 결정성) + 깊게 두기, 컴퓨터 3개(1단계 < 60단계), 방 통합 1개(연습 + 시간 넘김), e2e games.e2e.ts castles-of-burgundy(PC + 휴대폰 실제 행동 70번, 320px 넘침 없음, 기권으로 결과)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 00:06:00 +09:00
EJClaw
609cd8b410 사건 파일 결과 창: 함께 풀기는 모두 같은 순위라 '무승부예요'로 나오던 것을 '🎉 사건을 해결했어요!' / '사건을 풀지 못했어요'로, 소리도 해결이면 이김·아니면 짐
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 23:49:29 +09:00
EJClaw
bdb415aff6 핫스트릭 컴퓨터: 60레벨 시뮬레이션 400→200번. 400번이면 혼자서 한 수 최대 36ms라 전체 테스트를 병렬로 돌릴 때 서버의 컴퓨터 한 수 예산(50ms)을 넘어 'slow bot move' 경고로 bots.room.test가 가끔 실패했음. 봇 테스트 기준도 한 수 40ms 미만으로
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 23:47:48 +09:00
EJClaw
74f37131ea Merge branch 'wip/game-case-file' into codex/owner/grp_discord_joke-app
# Conflicts:
#	apps/web/src/games/help.test.ts
#	apps/web/src/games/registry.ts
#	apps/web/src/lib/catalog-ui.ts
#	docs/games/README.md
#	packages/games/package.json
#	packages/games/src/index.ts
#	packages/shared/src/catalog.ts
2026-10-15 23:46:31 +09:00
EJClaw
3b8a717888 새 게임 사건 파일: 직접 지은 협력 추리 게임(1~5명). 정해진 날짜·시간 안에 단서를 골라 읽고(이동 시간·야근·돋보기·조언), 마지막에 객관식 수사 보고서로 점수와 등급(S/A/B/미해결)
- 엔진 packages/games/src/case-file/(types·index·cases): 의뢰→수사→보고서→결과, 함께 풀기(반장 돌아가며/투표/아무나)·따로 겨루기, 시간·야근·피로, 열림 규칙(OR)·깊이 보기로 열림, 아침 소식, 조언 감점, 남은 시간 보너스, 한 사람만 읽기, 팀 답 다수결·동점 처리, 시간 초과·자리 비움·나가기
- 사건 3개(c1·c2·c3)를 docs/games/case-file-cases.md 글 그대로 cases/<id>.ts로 옮김(서버 전용). 웹은 types 모듈(라벨·스키마)만 가져오고, view에는 읽은 단서 본문만 나감
- 옵션: 문서 §2 전부(사건·모드·결정 방식·하루 시간·야근·돋보기·조언·남은 시간 보너스·아침 소식·읽기 모드·고르기/보고서/전체 제한 시간). kidSafeChat은 방 채팅을 그대로 쓰므로 방 설정의 채팅 필터로 대신(문서 구현 메모)
- 컴퓨터 상대 없음(문서 §8.7, BOT_GAMES에 넣지 않음)
- 웹 apps/web/src/games/case-file/: 수사 막대(날짜·시각·돋보기·조언·피로·반장·타이머), 탭 [단서·보고서·결과] [기록] [자료] [메모], 종이 서류 본문 카드(16px 이상), 지도, 장소별 단서 카드(이동+시간·🔍·야근·추천), 두 번 눌러 확정, 투표, 보고서, 등급 도장·문제별 답·풀이·놓친 단서, 30초 요약·도움말
- 등록: GAMES·CATALOG·GAME_UI·GAME_ICON·여럿이 파티 탭, @bg/games/case-file/types 내보내기, docs/games/README.md, e2e/games.e2e.ts
- 테스트: 사건 데이터 검사(id·여는 조건·도달·이동표·문제·점수표·고운 말·빠듯한 길을 실제 엔진으로 따라가 해결), 규칙 30여 개(문서 §10), 무작위 판(1~5명·옵션 7조합) 비밀 유출·JSON 왕복·결정성, onTimeout 합법, 방 통합(의뢰·반장·보고서·따로 겨루기 시계), 웹 빌드 결과물에 사건 본문·정답·풀이가 없는지 검사(no-case-text.test.ts), E2E(PC+휴대폰, 한 사람만 읽기 비밀·깊이 보기·하루 마치기·보고서·결과, 320px 가로 넘침 없음)
- 문서: case-file.md 구현 메모, case-file-cases.md c2 빠듯한 길 수정(원래 길은 열림 조건상 갈 수 없었음)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 23:43:31 +09:00
EJClaw
8f59a99d7d Merge branch 'wip/game-tichu' into codex/owner/grp_discord_joke-app
# Conflicts:
#	apps/web/src/games/help.test.ts
#	apps/web/src/games/registry.ts
#	apps/web/src/lib/catalog-ui.ts
#	docs/games/README.md
#	e2e/games.e2e.ts
#	packages/games/package.json
#	packages/games/src/bots/index.ts
#	packages/games/src/index.ts
#	packages/shared/src/bots.ts
#	packages/shared/src/catalog.ts
2026-10-15 23:32:24 +09:00
EJClaw
4f69f19bf9 새 게임 티츄: 4인 2:2 팀전(원작, 1,000점) 기본 + 4인 개인전·3인(더미)·6인 3:3 변형, 그랜드/스몰 티츄, 끼어드는 폭탄, 참새 소원, 파티 모드
- 엔진 packages/games/src/tichu/: combo.ts(조합 판정·봉황 가장 센 해석·폭탄 비교·소원 의무·조합 찾기, 화면도 @bg/games/tichu/combo로 같이 씀), index.ts(그랜드 → 교환 → 플레이 → 용 주기 → 라운드 결과 상태 기계), bot.ts
- 옵션 전부: mode(team/individual/threechu/tientsin), targetScore, threechuHands, grandTichu, direction, bombTiming + bombWindowSeconds("카드 모으는 중" 폭탄 창, 폭탄 유무와 상관없이 같은 대기), wishRule(enforce/penalty), trickHistory(last/all), party(두 배·점수 뒤집기·손패 돌리기·평범, 연속 없음), turnSeconds, exchangeSeconds
- 비공개: 남의 손패·남은 6장·교환 전 더미. 카드 ID가 라운드마다 다시 쓰여 새 라운드에 지난 play 기록을 지움. 탑 무늬 ID는 b(p2 같은 플레이어 id와 겹침 방지)
- 컴퓨터: 손패 나누기 비용으로 가장 약한 조합부터, 짝꿍 트릭은 패스, 폭탄·용은 상대가 곧 나갈 때, 티츄/그랜드 판단, 교환(짝꿍 좋은 카드·상대 개와 약한 낱장), 패널티 모드에서도 소원 지킴, 레벨 1~60
- 화면 apps/web/src/games/tichu/: 52장은 PlayingCard(4색), 참새·개·봉황·용은 직접 그린 SVG. PC 십자 배치·휴대폰 칩 줄, 손패 7장×2줄(320px), 고른 카드 실시간 "풀하우스(9) · 낼 수 있어요", 추천 조합 칩, 소원 시트, 폭탄 목록, 교환 칸 3개(추천대로 채우기·다시 고르기), 용 주기, 라운드 결과 표, 점수판·라운드 기록·직전 트릭·나온 카드 표, 소리·흔들림·배너, 도움말·30초 요약
- 등록: GAMES·BOT_STRATEGIES·BOT_GAMES·CATALOG·GAME_UI·GAME_ICON·카드·패 탭, docs/games/README.md, result-score 테스트에 300점 옵션, e2e/games.e2e.ts(PC + 휴대폰 3대, 1라운드 끝 → 2라운드)
- 문서 docs/games/tichu.md에 구현 메모(정한 것) 추가
- 검증: tichu 64개, web games 224개, server 240개, bots·result-score 161개, 타입 검사·웹 빌드, E2E_PORT=4603 bun e2e/games.e2e.ts tichu 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 23:31:37 +09:00
EJClaw
efa7adc0c2 Merge branch 'wip/game-hot-streak' into codex/owner/grp_discord_joke-app
# Conflicts:
#	apps/web/src/games/help.test.ts
#	apps/web/src/games/registry.ts
#	apps/web/src/lib/catalog-ui.ts
#	docs/games/README.md
#	e2e/games.e2e.ts
#	packages/games/package.json
#	packages/games/src/bots/index.ts
#	packages/games/src/index.ts
#	packages/shared/src/bots.ts
#	packages/shared/src/catalog.ts
2026-10-15 23:29:17 +09:00
EJClaw
8aad123222 새 게임 핫스트릭: 마스코트 넷의 카드 경주에 티켓으로 거는 파티 게임(2~10명, 놀이용 가상 돈)
- 엔진 packages/games/src/hot-streak/(cards·rules·race·index·sim·bot): 뱀 순서 티켓 뽑기(안전/위험 면) → 비밀 카드 넣기 → 경주 → 정산, 경주 3번
  - 경주는 서버 타이머가 flipSeconds마다 카드 한 장씩(timeoutPlayers 한 자리 + timeoutNotBefore, 끊겨도 빨라지지 않음), 모두 [빨리 보기]면 끝까지 바로
  - 카드 53장·충돌·기어가기·꺾기·초록 카드·허들·경주로 접기(13→10→7→3→0)·시상대 공동 실격·사이드 질문 12개 판정
  - 섞을 때마다 카드 id 접미사(#gen)를 새로 붙여 유출 검사가 헷갈리지 않음
  - §2 옵션 13개 모두: bettingMode(9~10명 상금 나누기 포함), races, finalBet, draftStart, reverseBets, cardsPerRace, burn, spicyDeck, hurdles, potScale, lifeStory, turnSeconds, flipSeconds
- 컴퓨터: 공개 정보로 덱을 추정해 몬테카를로 경주(레벨 1: 30번 ~ 60: 400번), 티켓·두 배·카드 넣기·상금 나누기 기대값, humanBest
- 화면 apps/web/src/games/hot-streak/: 직접 그린 SVG 마스코트(곰·핫도그·아귀·여왕)와 카드, PC 가로·휴대폰 세로 경주로, 경주 기록을 한 박자 늦게 다시 그리기(폴짝·쾅·실격·등수·접기), 티켓 더미·두 배·비밀 카드·상금 나누기·정산·최종 결과(인생 결과), 도움말·30초 요약
- 등록: GAMES·BOT_STRATEGIES·BOT_GAMES·CATALOG·GAME_UI·GAME_ICON·여럿이 파티 탭, docs/games/README.md, 설계 문서 §13 구현 메모(정한 세부 규칙)
- 테스트: 엔진 64개(§10 체크리스트·§5.8 예시·무작위 대국·시간 초과만으로 끝·유출 없음), 컴퓨터 15개, 도움말 2개, 방 통합 3개, e2e/games.e2e.ts hot-streak(PC + 휴대폰, 320px 넘침 확인)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 23:28:18 +09:00
EJClaw
97969a87bd Merge branch 'wip/game-gemblo' into codex/owner/grp_discord_joke-app
# Conflicts:
#	apps/web/src/games/registry.ts
#	apps/web/src/lib/catalog-ui.ts
#	docs/games/README.md
#	e2e/games.e2e.ts
#	packages/games/package.json
#	packages/games/src/bots/index.ts
#	packages/games/src/index.ts
#	packages/shared/src/bots.ts
#	packages/shared/src/catalog.ts
2026-10-15 19:41:49 +09:00
EJClaw
b02c9870cf 새 게임 젬블로: 육각 보석 블록 땅따먹기(2~6명), 원작 인원별 구역·시작점과 5인 장애물, 변형 규칙을 방 설정으로
- 엔진 packages/games/src/gemblo/(board·options·types·index·bot): 463칸 판(3인 241·4인 295·듀오 157칸), 블록 18개 72칸(방향 74/뒤집기 포함 92개 미리 계산), 같은 색 변 맞댐 금지, 꼭짓점 이음선(한 블록이 사이 두 칸을 덮으면 막힘, 두 블록 틈은 통과), 놓을 곳 없는 색 자동 끝남, 남은 칸 점수·공동 순위
- 방 설정 §2 전부: 자리, 2명 2색/3색/듀오, 3명 1색/2색, 5명 장애물 자동/직접 고르기/없음, 이음선 막힘, 뒤집기(기본 허용), 점수(남은 칸/블로커스 보너스), 팀전(2명씩·3명씩), 금색 방해 블록 0/3/6, 이음점 표시, 시간(한 번당·피셔), 시간 초과 처리(자동 배치/넘김/끝), 연속 자동 한도, 무르기
- 합법 배치: 이음점 × 블록 × 방향 × 맞출 칸, (블록·방향·기준 칸) 도장으로 중복 제거, apply·legalActions 수 ms
- 컴퓨터: 큰 블록 + 내 이음점 늘리기 + 남의 이음점 막기 + 초반 가운데로, 상위 80개만 자세히, humanBest 1~60단계, 한 수 10ms 안팎
- 화면 apps/web/src/games/gemblo/: 납작한 육각 SVG 판(안 쓰는 칸 흐리게, 보석 색 + 색약용 무늬), 마우스 미리보기·휠/R 돌리기·F 뒤집기, 휴대폰 칸 누르기·끌어 옮기기·[놓기], 이음점을 누르면 그 점을 덮는 합법 배치를 차례로, 두 손가락 확대·이동과 [확대]/[전체], 키보드 조작, 5인 장애물 고르기·놓기, 무르기·기권, 끝나면 색별 남은 블록, 소리·애니메이션, 도움말·30초 요약
- 등록: GAMES·BOT_STRATEGIES·BOT_GAMES·CATALOG·GAME_UI·GAME_ICON·판·주사위 탭, 운 제외(NO_LUCK), docs/games/README.md, docs/games/gemblo.md(구현 결정 13장)
- 테스트: 규칙 30개(문서 §10 전부, 5인 장애물 시드 100개, 클라이언트 판정 = validate 1만 개, 무작위 대국 11가지 모드), 컴퓨터 4개, 도움말 2개, 방 통합 2개(연습 한 판, 5명 직접 고르기 + 시간 초과만 하는 사람), e2e games.e2e.ts gemblo

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 19:40:45 +09:00
EJClaw
88db031d0a 새 게임 젝스님트: 숫자 카드를 동시에 몰래 내고 작은 수부터 줄 끝에 붙이기, 여섯 번째 카드면 앞의 다섯 장(소머리 = 벌점)을 가져가는 2~10명 카드 게임
- 엔진 packages/games/src/six-nimmt/(options·rules·types·index·bot): 104장 소머리(합 171), 규칙 1~4, 동시에 몰래 고르기(모두 고르기 전엔 바꾸기 가능, 마지막 사람이 고르면 공개), 작은 카드 줄 고르기·양쪽 끝 같은 차이 자리 고르기에서 멈춤, 라운드 합산·66점(또는 라운드 수) 종료·20라운드 안전장치
- 옵션 전부: 카드 구성(104장/인원×10+4 섞기/펼쳐 골라 가기 프로 2~6명), 양쪽 끝 붙이기, 작은 카드 자동, 30주년판 특별 카드 4종(짝홀·산 오르기·점프하는 소 연쇄·숫자 뒤집기), 끝 점수/라운드 수, 나온 카드 표, 제한 시간
- 시간 초과·나가기: 지금 줄 기준 가장 안전한 카드·소머리 적은 줄, 3번이면 자리 비움(5초), 나간 사람은 바로 자동, 1명 남으면 끝
- 컴퓨터: 카드마다 상대 카드를 흉내 내어 가져갈 소머리 평균(1단계 4번 → 60단계 48번), humanBest 실수, 41단계 이상 숫자 뒤집기·대기 카드 보고 줄 고르기
- 화면 apps/web/src/games/six-nimmt/: 소머리 색 카드, 줄 4개 + 빨간 6번째 칸, 공개 카드 줄과 한 장씩 놓이는 재생(줄 빛남·흔들림·"+🐮" 배너·음매 소리), 손패 미리 보기("2번 줄 3번째"/"⚠ 가져감"/"⬇ 너무 작음"), 뒤집기 토글, 줄 고르기 버튼(추천), 프로 뽑기, 라운드 결과 창, 최종 표, 점수표·나온 카드 표·기록, 휴대폰 320px, 도움말·30초 요약
- 등록: GAMES·BOT_STRATEGIES·BOT_GAMES·CATALOG·GAME_UI·GAME_ICON·카드·패 탭, docs/games/README.md, 설계 문서에 정한 것 기록
- 테스트: 규칙 46개(문서 §10 예시 전부, 무작위 대국 옵션 7종 JSON 왕복·결정성·정보 누출·카드 총수·onTimeout 합법), 컴퓨터 25개(옵션 7종 × 2·5·10명, 60단계 대 1단계), 도움말 2개, 방 통합 4개, E2E six-nimmt·six-nimmt-pro

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 19:33:32 +09:00
EJClaw
8620c82ca8 새 게임 6개 설계 문서: 티츄·핫스트릭·버건디의 성·사건 파일(디텍티브 대신 새로 만든 협력 추리, 사건 3개)·젝스님트·젬블로
- 게임마다 _TEMPLATE.md 12개 절: 공식 규칙, 방 설정으로 넣을 변형 규칙(기본값은 원작), 엔진 설계, 화면, 테스트, 출처
- 사건 파일은 원작 사건 글을 쓰지 않고 진행 방식만 빌림. 사건 3개 전체 글은 case-file-cases.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 18:53:41 +09:00
EJClaw
57351fd9d6 휴대폰에서 채팅을 보낸 뒤에도 키보드 유지: "보내기" 버튼을 누르면 포커스가 버튼으로 넘어가 입력 칸이 빠지고 키보드가 내려가던 것을, 버튼의 pointerdown/mousedown 기본 동작을 막아(lib/chat-input keepFocus) 포커스를 입력 칸에 두고, 보낸 뒤에도 입력 칸에 포커스를 다시 줌. 방 채팅(ChatPanel)·그림 맞히기·마피아·라이어 게임 채팅 모두. Esc로 빠져나가기와 포커스가 빠질 때 "입력 중" 끄기는 그대로. chat.e2e.ts(휴대폰 시트에서 보내기 탭)와 games.e2e.ts(catchmind·mafia·liar 보내기 버튼)에 확인 추가, docs/07에 한 줄
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 10:25:06 +09:00
EJClaw
b61be627c9 채팅 소리 기본 크기를 게임 소리의 80%로 올리고(60%는 너무 안 들린다는 의견), 관리자 사이트 설정에 "채팅 소리 크기"(게임 소리의 0~200%, 정수, 기본 80%)를 추가. 0%면 채팅 소리 없음. 각자의 소리 크기(0~100)는 그대로 곱해짐. 저장하면 /api/config와 방 정보(RoomView.chatSound)로 열린 방에도 바로 적용. 설정 화면에 저장 없이 그 값으로 울려 보는 "들어 보기" 버튼. feedback.test.ts·admin.test.ts·admin.e2e.ts에 확인 추가, docs/14-admin.md 표에 항목 추가
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 00:45:33 +09:00
EJClaw
42e8d7650b 채팅 "뽁" 세기 줄임: 귀를 때린다는 의견에 크기를 게임 소리의 90%→60%로 낮추고, 시작(attack)을 2ms→12ms로 부드럽게 해서 "탁" 튀는 느낌을 없앰. 음(380→1150Hz, 0.08초)·소리 크기 설정·몰림 한 번·지난 채팅 조용히는 그대로. feedback.test.ts 맞춤
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 11:38:05 +09:00
EJClaw
6b5e29a2e2 채팅 소리를 "한 번만 뽁"으로: 물방울 두 개 "뽀록"에서 첫 물방울 하나만(380→1150Hz로 빠르게 올라가는 사인, 0.08초). 게임 pop(700→1400Hz)보다 낮게 시작하고 짧고 작아서 구분됨. 크기(게임 소리의 90%)·소리 크기 설정·몰림 한 번·지난 채팅 조용히는 그대로. feedback.test.ts와 chat.e2e.ts 맞춤
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 10:07:33 +09:00
EJClaw
aed4dd0fce 채팅 소리를 메신저 같은 "뽀록"으로: 두 음이 올라가는 "띠릭"은 맞음·내 차례 같은 설정/게임 소리와 헷갈려서, 낮은 데서 빠르게 미끄러져 오르는 물방울 두 개(380→1150Hz, 520→1500Hz)로 바꿈. 크기(게임 소리의 90%)·소리 크기 설정·몰림 한 번·지난 채팅 조용히는 그대로. feedback.test.ts와 chat.e2e.ts의 음 확인도 맞춤
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 09:58:24 +09:00
EJClaw
b7d5b3ad75 채팅 소리(스타크래프트 같은 "띠릭"): 새 채팅 줄마다(내가 보낸 줄도) 맑은 두 음이 올라가는 짧은 소리. 크기는 게임 소리 기준(0.15)의 90%로 소리 크기 설정을 그대로 따르고, 소리 끄기면 안 남. 몰려 온 줄은 한 번만. 방에 (다시) 들어올 때 서버가 다시 보내는 지난 채팅은 replay 표시로 조용히. 마피아·라이어 게임 안 채팅도 같은 소리. feedback.test.ts, room.test.ts, chat.e2e.ts에 확인 추가
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 09:42:31 +09:00
EJClaw
e0139f412e PC 창을 줄였을 때(720~1099px)도 채팅: 옆 채팅 칸이 없는 폭이면 방 막대에 💬 채팅 버튼(전에는 휴대폰 폭에서만 보여 이 구간엔 채팅이 아예 없었음). 넓은 폭에선 버튼과 시트를 숨김. chat.e2e.ts에 900/760px 확인 추가
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 09:32:16 +09:00
EJClaw
92aebb6a19 문서: 마피아 채팅 예산 문구를 관리자 도배 방지 설정(기본 꺼짐)에 맞게
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 09:12:08 +09:00
EJClaw
77e9688876 관리자 사이트 설정에 "채팅 도배 방지" 켜기/끄기(기본 끄기): 끄면 채팅·입력 중 신호에 속도 제한이 전혀 없고, 켜면 접속마다 초당 50개(한 번에 200개)와 해석 전 원시 한도. 메시지마다 설정을 읽어 저장하면 열린 접속에도 바로 적용. 게임 조작 한도와 잘못된 메시지 차단은 그대로
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 09:08:54 +09:00
EJClaw
0bff06fa3e 웹소켓 도배 방지를 JSON 해석 전으로: 채팅·게임 한도를 합친 원시 한도(초당 70, 최대 240)를 파싱 전에 먼저 적용해 도배가 메시지마다 파싱 비용을 쓰지 않게(gateway.test.ts). 문서에서 지운 lastChatAt 설명 제거
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 09:04:07 +09:00
EJClaw
4d1deb8346 채팅을 따로 분리해 속도 제한 없이: 방 채팅·마피아·라이어·그림 맞히기(그리기 전) 채팅의 줄 간격 제한(chat-pace)과 브라우저 대기열을 없애 치는 대로 바로 보냄. 서버 연결당 공용 한도(초당 20개)를 채팅·입력 중 신호가 같이 써서 빠르게 치면 15번째 줄부터 조용히 사라지던 문제도: 채팅은 별도 한도(초당 50, 최대 200, 매크로 도배 방지용)로 분리. 게임 채팅은 보내는 동안 게임 버튼을 잠그지 않음(pending 미설정)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 08:58:17 +09:00
EJClaw
13a89a645e 새 게임 블랙잭: 딜러(하우스) 상대 1~7명·놀이용 칩. 공식 규칙(6벌 S17·블랙잭 3:2·A/10 peek·아무 두 장 더블·DAS·4손패 스플릿·에이스 한 장)을 기본값으로, 한국 하우스 룰(5·6카드 찰리, 7-7-7 보너스 3:1, 배당 6:5·2:1·1:1, H17, 더블 9~11·10~11, 에이스 자유 히트·다시 스플릿, 레이트 서렌더, 인슈어런스)을 방 설정으로
- 엔진 packages/games/src/blackjack/(options·types·rules·index·bot): 베팅→인슈어런스→플레이→딜러→결과 단계 상태 기계, 비공개는 딜러 홀 카드와 슈뿐(재셔플마다 카드 id 유일), 칩은 하우스 상대로 정산
- 컴퓨터: 기본 전략(S17 차트) + 레벨 1~60(쉬움은 딜러 흉내·인슈어런스 가끔, 어려움은 차트대로·인슈어런스 거절)
- 웹 apps/web/src/games/blackjack/: 초록 테이블·손패·단계별 버튼·방 설정 변형, 30초 요약·도움말, 표준 카드 아트 재사용
- 등록: GAMES·BOT_STRATEGIES·BOT_GAMES·CATALOG·GAME_UI·GAME_ICON·게임 탭, 문서(games/blackjack.md·README·로드맵·결정 사항), e2e/games.e2e.ts
- 검증: 엔진·봇 테스트, 무작위 플레이(여러 옵션) JSON 왕복·정보 누출 없음, 전체 테스트 2,611개·타입 검사·웹 빌드 통과, bun e2e/games.e2e.ts blackjack 통과

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-14 05:45:41 +09:00
EJClaw
71bdfd201a 혼자인 대기실에서 브라우저 뒤로가기(홈)로 나가면 빈 방이 10분 동안 남던 문제: 다른 사람이 없고 게임 전이면 detach를 나가기로 처리해 방을 바로 닫음. 방 안 📖 규칙도 팝업으로(규칙 페이지로 넘어가며 방을 떠나지 않게), e2e/room-back.e2e.ts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 05:03:12 +09:00
EJClaw
b93228e5af 사과 게임 무제한: 스톱워치(시작부터 더 지울 사과가 없거나 여기까지 할 때까지, 0.1초 단위)와 💡 힌트(합 10 묶음 하나를 나에게만 노란 점선 상자로), 결과창·순위·요약에 걸린 시간과 힌트 횟수
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 04:52:19 +09:00
EJClaw
96e8cdeb24 병합: 루미큐브 앱 규칙 기본 + 끌어다 놓는 판(움직이는 동안 모두에게 보임)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 04:43:03 +09:00
EJClaw
7f4b86e432 루미큐브: 루미큐브 앱 규칙을 기본으로(시간 초과는 무조건 되돌리고 1장, 되돌리기는 차례 처음으로, 30초 추가), 타일을 끌어다 칸 판에 놓고 합치기, 움직이는 동안 모두에게 보이게
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 04:42:38 +09:00
EJClaw
1f0b52685e e2e: 섯다에서 두 사람이 다이하면 남은 사람이 [카드 공개]를 고르고 모두에게 패가 보이는지(seotdaFold)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 04:33:24 +09:00
EJClaw
ddd7d72050 병합: 섯다·포커 혼자 남으면 카드 공개 여부 고르기
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 04:30:55 +09:00
EJClaw
966bc3c5ef 섯다·포커: 다른 사람이 모두 죽고 혼자 남으면 카드를 공개할지 고르기(카드 공개/공개 안 함, 시간 초과·나감·기본은 공개 안 함, 공개하면 모두에게 패와 족보를 뒤집어 보여 주고 기록에 남김, 컴퓨터도 센 패면 가끔 공개)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 04:27:55 +09:00
EJClaw
1ba83766d0 휴대폰 채팅 시트: 새 메시지가 올 때마다 입력 칸 포커스가 빠져 키보드가 닫히던 문제(Sheet가 onClose가 바뀔 때마다 포커스를 다시 잡음) — 열 때 한 번만 포커스를 옮기게
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 04:21:43 +09:00
EJClaw
18f0530237 설정을 팝업으로: 방 안에서 설정을 열어도 방에서 나가지 않게 방 막대·헤더 계정 메뉴의 ⚙️ 설정을 화면 설정 팝업으로(설정 페이지와 같은 화면 설정 공용, 헤더 팝업에는 내 계정·기록 링크), e2e/settings.e2e.ts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 04:15:08 +09:00
EJClaw
73b929739d 문서: 마피아·라이어 채팅 속도 제한을 새 규칙(한 번에 6줄, 그 뒤 0.3초에 한 줄)으로
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 04:09:37 +09:00
EJClaw
ff3c53ab4a 채팅 연타가 몇 초씩 밀리던 문제: 브라우저가 0.55초(마피아·라이어 0.75초)에 한 줄씩만 내보내던 대기열과 게임 채팅 0.7초 간격 제한을 없애고, 방 채팅·마피아·라이어가 같은 속도 규칙(한 번에 6줄, 그 뒤 0.3초에 한 줄)을 쓰게. 사람이 치는 속도로는 기다리지 않고 바로 올라감
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 04:09:29 +09:00
EJClaw
cf2903dc75 할리갈리: 1280×800 같은 낮은 화면에서 내 자리가 종과 겹치지 않게 자리 여백을 줄이고 차례 말표를 이름 위 테두리에, 종을 때리는 손이 땡/삐 말풍선 위로 보이게
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 02:04:24 +09:00
EJClaw
7dccc8e713 할리갈리·바퀴벌레 포커 화면 다시 만들기
- 할리갈리: 자리마다 뒷면 덱 더미(장수만큼 쌓임)와 펼친 더미를 나란히(펼친 쪽이 종 쪽), 뒤집으면 카드가 덱에서 들려 3D로 뒤집혀 내려앉음, 차례 말표·내 덱 들썩임(덱을 눌러도 뒤집기), 종 판정 때 친 사람 쪽에서 손바닥이 날아와 종을 때리고 파동(정답 노랑/오답 빨강), 정답자 금빛·"+N장", 오답 "-N장", 새 카드 뒷면, 말풍선은 종 바로 위
- 바퀴벌레 포커: 펠트 테이블(왼쪽)과 행동 칸(오른쪽, 휴대폰은 아래). 상대 자리 판(손패 뒷면 부채, 앞마당은 벌레별 실제 카드 더미+장수 배지·위험 테두리), 가운데 "건넨 사람 ➜ 받는 사람"·기울어 놓인 카드·주장 말풍선, 판정 때 카드가 3D로 뒤집히고 "진짜/거짓" 도장 → 앞면 카드가 가져가는 사람 앞마당으로 날아가 더미에 내려앉음, 내 손패 카드 부채
- 두 게임 30초 규칙 그림도 같은 테이블·카드 모양으로, 문서 §9 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 01:37:47 +09:00
EJClaw
18ef402a6a 게임 속도 배율: 1배도 애니메이션·연출·컴퓨터 생각 시간을 예전의 1.5배로 늦추고, 관리자 사이트 설정 "게임 속도 배율"(1/16~16배, 기본 1)로 나눠 조절. 저장하면 열린 방에도 바로 적용(RoomView.gameSpeed 재전송)
- 서버: SiteSettings.gameSpeed, /api/config에 노출, 컴퓨터 생각 시간(defaultBotDelay)과 마피아·라이어 컴퓨터가 살펴보는 간격에 BOT_SLOWDOWN(1.5)/배율. 게임이 정한 반응 시각(원카드 외치기)은 그대로
- 웹: lib/motion.ts — .game-layout 안 CSS 애니메이션·트랜지션은 useMotionScope가 playbackRate로, Web Animations는 fxAnim, 연출 타이머(배너 유지·다음 단계·복사본 정리·숫자 세기·다시 보기 한 칸)는 fxMs. 채팅·role="timer"·규칙 시간·꾹 눌러 보기는 제외
- 관리자 사이트 탭에 배율 버튼(1/16~16)과 직접 입력
- 테스트: 배율 검증(API 400/200, 열린 방 즉시 반영), 컴퓨터 생각 시간 배율, motion 단위 테스트, e2e/speed.e2e.ts(돌 애니메이션 재생 배율·컴퓨터 응답 시간), 관리자 e2e에 배율 저장
- 문서: 14-admin §5, 07-ui-ux, 06-lobby-rooms, 13-decisions, README

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 01:24:25 +09:00
EJClaw
5e8f5b821f 결정 사항: 섯다 한게임 기본·옵션 갱신, 게임 그림 출처 표
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 23:31:02 +09:00
EJClaw
eeea9a468b 병합: 체스(Cburnett)·마작(Shizhao) 실제 그림
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 23:26:32 +09:00
EJClaw
be1ee44b17 체스·마작 실제 그림: 체스 기물은 Cburnett(CC BY-SA 3.0), 마작패는 Shizhao 퍼블릭 도메인 SVG
- 체스: 직접 그린 기물을 Wikimedia Commons Cburnett 12장(Chess_{k,q,r,b,n,p}{l,d}t45.svg)으로 바꿈.
  최소화 SVG(합계 약 11 KB)를 chess/pieces/에 두고 art.ts의 pieceSrc()로 판 SVG 안 <image>로 그림
  (Vite가 체스 청크에 data URL로 넣음). 미끄러짐·내려앉기·잡힘·끌기·키보드·aria는 그대로.
  30초 규칙 요약 그림판도 같은 기물, 다크 모드에서 판 밖 흑 아이콘에 옅은 테두리. 규칙 화면에 출처 한 줄.
- 마작: 직접 그린 패 앞면을 Shizhao 컬러 세트 34장(MJ*.svg, PD-self / 서풍 CC0)으로 바꿈.
  윤곽·흰 바탕을 지우고 svgo로 줄인 37장(적도라 5mr·5pr·5sr 포함, 약 120 KB)을 mahjong/tiles/에 둠.
  패 몸통·뒷면·선택·흐림·애니메이션·aria는 그대로, 왼쪽 위에 숫자/한글(동·남·서·북·백·발·중)을 겹치고
  작은 패(30px 미만)에서는 크게 써서 버림패·휴대폰 손패에서도 읽힘. 마작 청크에만 들어감. 규칙 화면에 출처 한 줄.
- 출처 파일 ATTRIBUTION.txt(각 폴더), docs/games/chess.md §9 "기물 그림", docs/games/mahjong.md §9.2 "패 그림".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 23:26:20 +09:00
EJClaw
e7d1c1d90c 병합: 움직임 더하기 2차(루미큐브·마피아·라이어·바둑·클루·오목·포커)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 22:37:33 +09:00
EJClaw
404d2a3261 도둑잡기 규칙에 트럼프 카드 그림 출처
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 22:37:24 +09:00
EJClaw
6131e74511 병합: 트럼프 J·Q·K·조커 실제 카드 그림(Dmitry Fomin, CC0)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 22:36:53 +09:00
EJClaw
843786f687 움직임 더하기 2차: 루미큐브·마피아·라이어·바둑·클루·오목·포커
- 루미큐브: 옮긴 타일이 원래 자리에서 미끄러져 가고, 남이 바닥에 낸 타일은 그 사람 칸에서 날아옴. 가져온 타일은 남은 타일 더미에서 받침대로 날아오고, 남이 가져가면 뒤집힌 타일이 그 사람 칸으로 날아감. 배너를 공통 useBanner로 바꾸고 "루미큐브!"·"판 끝"·승리 배너 추가
- 마피아: 밤에는 화면이 남색으로 어두워지며 달, 아침에는 해가 떠오름. 득표 막대가 한 줄씩 자라고, 탈락한 사람 칸이 뒤집히며 흐려짐. 탈락·살았다·버텼다·조용한 밤·이긴 팀 배너를 차례로
- 라이어: 득표가 한 줄씩 나온 뒤 지목된 사람에게 스포트라이트와 흔들림, "잡았다!"/"헛다리!"·동점·정답/땡·승리 배너
- 바둑: 패스·계가 배너, 계가 때 집 표시가 차례로 나타나고 결과 점수가 0부터 올라감, 승리 배너
- 클루: 말과 흉기가 새 자리로 튀어 오르며 미끄러져 감, 추리한 세 장이 사건 봉투로 날아가고, 보여 준 카드는 뒤집히며(남에게는 뒷면 카드가 날아감)
- 오목: 금수 자리를 누르면 빨간 ✕와 "금수" 글자, 판이 흔들림(키보드 Enter도 같은 안내). "오목!"·승패 배너
- 포커: 쇼다운·인디언 이마 카드가 뒷면이 돌아간 뒤 앞면이 돌아 나오는 진짜 뒤집기로
- 모두 누구의 행동이든 화면 변화에 반응하고, 클릭을 막지 않으며, 동작 줄이기 설정을 따름. 게임 문서 UI 절에 반영

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 22:36:44 +09:00
EJClaw
aac365606a 트럼프 카드 J·Q·K·조커에 실제 카드 그림: Dmitry Fomin의 English pattern 그림카드 12장과 Atlas 조커 2장(Wikimedia Commons, CC0)을 그림 부분만 잘라 WebP 14장(약 250KB, 따로 받는 파일)으로 넣고, 그림카드는 왼쪽 위를 비운 테두리 안에 그려 큰 모서리 글자를 그대로 둠. 포커·원카드·구십구 규칙에 출처 한 줄, 게임 문서 §9 반영
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 22:36:17 +09:00
EJClaw
a6b47be03f 병합: 도둑잡기 화면 개선(뽑기 방향 바로잡기·부채꼴 카드·애니메이션)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 22:28:54 +09:00
EJClaw
265a0c2ebf 도둑잡기 화면 개선: 뽑기 방향 제목을 "[아바타] 뽑는 사람님 → [아바타] 뽑히는 사람의 카드 N장"으로 바로잡고(내가/내 카드, 움직이는 화살표), 뒷면 카드와 내 손패를 손에 쥔 부채처럼 겹쳐 호로 펼침(띠 28px 미만이면 여러 줄), 뽑은 카드가 부채에서 들려 날아가기, 섞기 리플·내 손패 자리 바꾸기, 펠트 테이블·지난 뽑기·버린 짝 정리, 자리 카드 뒷면 부채
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 22:27:53 +09:00
EJClaw
1cf556b431 섯다: 3장 섯다를 한게임 방식으로 — 2장 받고 공개패 1장 고르기 → 1구 베팅 → 1장 더 → 2구 베팅 → 3장 중 2장 골라 승부
- 엔진: 공개패 단계(open)·액션, 공개패는 다른 사람 화면에 앞면, 최종 선택은 마지막 베팅 뒤(threePick=end), 옵션 threeOpen/threePick으로 예전 흐름 유지, 상태 v3(진행 중인 방은 예전 흐름)
- 컴퓨터: 광·4/7/9 열끗은 숨기고 평범한 패 공개, 상대 공개패를 패 범위에 반영
- 화면: 공개패 고르기 상자, 자리 표시·도움말·규칙·옵션
- 2장 섯다 기본(2장 한 번에)은 한게임 안내 그대로, 1장씩(전통)은 옵션
- E2E seotda3, 문서 §2·§5.2·§8

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 22:22:06 +09:00
EJClaw
9564e4604c 야단법석 달리기: 먼저 갈 선수를 고르는 동안 판 가운데에 '출발 준비!' 대신 누구 차례인지
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 22:05:40 +09:00
EJClaw
b1b6cccad4 야단법석 달리기 화면을 부루마불처럼: 네모난 고리 판(PC 9×8, 휴대폰 7×10, 출발 모서리가 결승), 가운데 입체 주사위·시상대·할 일 버튼, 말이 한 칸씩 걷기·화살표 미끄러짐·순간이동 날기, 능력·별·돌·결승 효과와 소리
엔진: 경주 기록 줄에 화면용 mv(이동 출발·도착 칸)와 die(굴린 눈) 추가, mv만 따라가도 말 자리가 맞는지 무작위 대국 테스트.
화면: replay.ts(기록 → 주사위·걷기·효과 순서) + 테스트, 문서 §9·§10.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 22:03:28 +09:00
EJClaw
d35b7207a3 병합 정리: 윷놀이 E2E가 앞 게임의 친구 화면을 잡던 문제, 고스톱 규칙에 화투 그림 출처, 문서(README·로드맵·결정 사항) 2차 묶음 반영
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:59:39 +09:00
EJClaw
2489627bcd 병합: wt2/seotda 2026-10-13 13:38:00 +09:00
EJClaw
606756868c 병합: wt2/ai-chat 2026-10-13 13:37:59 +09:00
EJClaw
91fcf1c83d 병합: wt2/one-card 2026-10-13 13:37:59 +09:00
EJClaw
647e9bd448 병합: wt2/g2-cards 2026-10-13 13:37:59 +09:00
EJClaw
764de1fe1a 병합: wt2/g4-party 2026-10-13 13:37:59 +09:00
EJClaw
43291606ce 병합: wt2/g3-tiles 2026-10-13 13:37:59 +09:00
EJClaw
085ddbaec3 병합: wt2/g1-board 2026-10-13 13:37:59 +09:00
EJClaw
99c25cb260 야단법석 달리기: 주사위·발걸음·능력·칸 효과·결승 소리, 말이 뛰는 움직임·넘어짐·메달, 뽑기 카드 등장; E2E: 그림 맞히기·클루·라이어·마피아 투표를 시간 무제한으로
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:37:26 +09:00
EJClaw
b6b9dbc963 섯다 화면 다시 만듦(한게임 섯다처럼): 초록 테이블·가운데 판돈·숫자 키 베팅 버튼·족보 도우미, 동전 날아가기·카드 나눠 주기·뒤집기·큰 글자 연출과 소리, 실제 화투 그림(Wikimedia Commons, CC BY-SA 4.0, 고스톱도 같이), 원·판돈 표기(돈 표현 검사에서 섯다만 예외), 문서·E2E
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:35:23 +09:00
EJClaw
8cde4fa525 섯다 엔진·컴퓨터 다시 만듦(한게임 섯다 기준): 원 단위(시작 100만원·기본금 1만원, v1 칩 방은 ×1000으로 옮김), 2장 한 번에 받기 기본, 20/40장, 베팅 규칙 111~444, 쿼터는 옵션, 땡잡이 3·7 아무 패·멍구사 9땡까지 기본, 시간 무제한, 베팅 기록·판별 손익을 view에
컴퓨터는 남은 패를 전부 따져 보고(맞대결·3명은 모든 경우, 큰 판은 3,000판 표본) 상대 베팅으로 패 범위를 좁혀 판돈 몫과 기댓값으로 결정.
1장만 받고 하프 한 번에 다이하던 버그(고정값 0.35 패 세기와 값 비율 비교) 고침, 회귀 테스트 추가.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:35:23 +09:00
EJClaw
4fa4c69725 뱅!·고스톱·스플렌더·바퀴벌레 포커·구십구 소리·애니메이션, 게임 문서에 소리·움직임, E2E에서 무제한 확인
- 모두 view 변화(기록·이전 view 비교)에 반응해서 컴퓨터·다른 사람 행동에도 소리와 움직임이 나옴, 처음 렌더·다시 보기는 건너뜀
- 뱅!: 총소리·개틀링·인디언·결투·판정 카드·다이너마이트·감옥·맥주·쓰러짐 배너
- 고스톱: 패 내기 "탁", 뒤집기, 먹기, 피 뺏기, 뻑·따닥·쪽·싹쓸이·폭탄·흔들기 배너, N고, 판 끝(마지막 판 승패 소리는 결과 창 하나만)
- 스플렌더: 보석·카드·귀족이 날아가고 보석 소리, 마지막 라운드 배너
- 바퀴벌레 포커: 건네기·판정 배너·앞마당으로 날아감·위험 경고음
- 구십구: 카드가 합계 다이얼로, 90 이상 두근, 바로 99 배너, 방향 바뀜, 목숨·탈락
- E2E: 구십구·바퀴벌레 포커를 무제한으로 진행하고 타이머가 안 보이는지 확인

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:31:24 +09:00
EJClaw
36c8033b65 라이어 게임: 설명·토론·투표·정답 맞히기 시간 무제한(할 일을 마칠 때까지, 연결 끊긴 사람은 유예 뒤 넘김), 설명·투표·지목 소리, 움직임
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:18:52 +09:00
EJClaw
92c9a41d83 원카드 화면: 따로 누르는 원카드 버튼(잡기 N초 세기), 카드 먹을 때 더미에서 한 장씩 날아가고 장마다 소리, 큰 벌칙은 판 흔들림·빨간 번쩍임, 공격 누적 숫자 세어 올라가기, 나눠 주기·섞기·내기·무늬/색 바꾸기 효과, 도움말·규칙·문서·E2E
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:15:18 +09:00
EJClaw
28590df429 원카드: 카드 내기와 원카드 외치기 분리(내면서 외치기 없앰), 잡기 전 보호 시간(1~3초, 기본 2초), 컴퓨터도 사람처럼 늦게 외치고 잡기, 한 턴 시간 무제한, 원카드 보너스 옵션
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:15:18 +09:00
EJClaw
743e5dc05e 마피아: 단계별 시간 무제한(토론·지목 투표·반론·찬반·밤, 모두 마치면 넘어감·연결 끊긴 사람은 유예 뒤 넘김), 밤·아침·판결 소리, 움직임
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:14:54 +09:00
EJClaw
2136916a28 컴퓨터 채팅 고침: 부르면 매번 빨리 대답(느리거나 모델 없으면 내장 대답), 혼잣말은 판에서 눈에 띈 일에만 드물게, 수와 어긋난 말("풀 베팅인데 쫄았네") 거르고 수 종류별 한마디
- 대답: 이름·이어 말하기·대화 중인 컴퓨터에 매번 대답, 입력 중에 온 말은 끝나고 대답, 모델 2.5초만 기다리고 내장 대답, 한 사람에게 1분 8번까지
- 모델 대기열 1칸(GPU 하나), 대답이 혼잣말보다 먼저, 혼잣말은 바쁘면 버림, 타자 0.7~3.5초
- 혼잣말: 센 베팅·다이·고/스톱 등 눈에 띈 수에만, 방 40초·컴퓨터 90초 간격, 시작 인사·끼어들기 없앰, 수의 뜻과 판 공개 정보(판돈·칩·점수)를 모델에 줌
- 수 종류(센 베팅·콜·체크/삥·다이/폴드·과감·안전·기권)별 내장 한마디, 어긋나거나 게임과 상관없는 말은 그걸로 바꿈
- 막말·지시문 되풀이 거름, 마피아·라이어 게임은 계획된 대사만

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:11:41 +09:00
EJClaw
94f7120a51 문서: 6개 게임 소리·움직임(§9.1), 요트·라스베가스·부루마불 무제한 시간 마감 규칙
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:09:19 +09:00
EJClaw
a6ace5b5e8 루미큐브·다빈치 코드·마작·라스베가스·부루마불·요트 다이스 소리·애니메이션: 상대·컴퓨터 행동도 화면 변화로 한 번만 울림(처음 들어올 때·재접속은 조용), 타일 놓기·뒤집기, 주사위 굴림, 말 한 칸씩 이동, 점수 통 튀기, 큰 순간 배너
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:09:19 +09:00
EJClaw
1b4c80a2df 요트 다이스·라스베가스·부루마불 차례 시간 '무제한' 표기 통일: 요트 '제한 없음'→'무제한', 요약은 '시간 무제한', 부루마불 무제한 마감 없음 테스트
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:09:19 +09:00
EJClaw
f6a0cdcf14 윷놀이 소리·움직임
- 던지기: 휙 + 가락 4개가 멍석에 떨어지는 딱딱 소리(떨어지는 순간에 맞춤), 윷·모 밝은 음, 빽도 내려가는 음, 낙 둔탁한 소리
- 가락마다 다르게 돌고 떨어진 뒤 한 번 튐, 결과 글자 튀어나옴(윷·모 빨강), 낙이면 가락 흔들림
- 말: 한 칸마다 작은 "콩"(튀는 움직임과 같은 때), 도착 시 잡기·업기·나기 소리와 고리(잡기 빨강, 나기 금색)
- 잡힌 말은 움직이는 말이 도착할 때까지 남아 있다가 튀어 오르며 사라짐
- 상대·컴퓨터 차례도 화면 변화로 같은 소리·움직임, 숨은 탭의 내 차례 소리는 방 화면에 맡겨 두 번 울리지 않게

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:08:18 +09:00
EJClaw
8175cebd2c 체스·장기·쿼리도 소리·움직임, 장기 상차림 시간 무제한
- 체스: 기물이 출발 칸에서 미끄러져 와 내려앉음(내가 끌어다 놓은 수는 제외), 캐슬링은 룩도 같이, 잡힌 기물(앙파상 폰 포함) 사라짐, 체크 칸 빛·말풍선 튀어나옴, 마지막 수 칸 살짝 나타남
- 체스 소리: 나무 기물 톡, 잡기, 캐슬링, 승진, 체크, 체크메이트 순간, 무르기, 기물 집기, 안 되는 칸 (fx.ts 순수 함수 + 테스트)
- 장기: 묵직한 기물 미끄러짐·내려앉기, 잡힌 기물 사라짐, 장군 궁 자리 고동, 상차림 마·상 하나씩 튀어나옴
- 장기 소리: 두꺼운 나무 "딱", 잡기, 장군·멍군·빅장, 외통 순간, 한수쉼, 무르기, 상차림 놓기 (fx.ts + 테스트)
- 장기 상차림 고르는 시간에 무제한(0) 추가, 방 설정 "자세한 설정"에서 30초·1분·3분·무제한 (기본 1분 그대로), 무제한이면 상차림 시계 숨김, 끊긴 사람만 접속 유예 뒤 자동 선택
- 쿼리도: 말 한 칸은 살짝 튀며, 점프는 높이 뛰어 넘음, 도착 칸 고리, 벽 내려앉기+먼지, 무르기로 빠진 벽 사라짐, 안 되는 벽 흔들림, 목표 도착 띠 깜빡임·금빛 고리
- 쿼리도 소리: 말 톡, 점프, 벽 끼우기, 안 되는 곳, 목표 도착, 무르기
- 상대·컴퓨터 수도 화면 변화로 같은 소리·움직임, 새로 열면 다시 재생 안 함, 숨은 탭 내 차례 소리는 방 화면에 맡김

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:08:18 +09:00
EJClaw
ac37a6a6d8 카드 게임 시간 무제한(우노·뱅!·달무티·고스톱·도둑잡기·포커·바퀴벌레 포커·99), 공통 카드 움직임(card-fx), 우노·달무티·도둑잡기·포커 소리·애니메이션
- 무제한(null): 차례 시계·타임아웃 없음, 자리 비움만 짧은 시계, 연결 끊김은 방 유예 뒤 자동 행동 그대로
- 포커는 리바이 고르는 시간도 무제한 가능, 고스톱은 고·스톱 선택 시간도 무제한 가능, 뱅!은 반응 시간·캐릭터 고르기도
- card-fx: 날아가는 카드·칩(ghost), 제자리 날아오기, 배너, view 변화 감지 훅(처음 렌더·다시 보기는 건너뜀)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:04:11 +09:00
EJClaw
b8966db2a6 그림 맞히기·클루: 그리기·차례 시간 무제한(출제자 정답 공개로 넘기기), 소리·움직임, 할리갈리·사과 게임 문서에 무제한
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:01:42 +09:00
EJClaw
5e1e74da18 오목·사목·오델로·바둑 소리·움직임, 바둑 사석 확인 무제한
- 공통(보드게임 8종용) board-motion: 직전 판 비교(useMoveDiff), 끝난 잔상 치우기(useAnimOver), 내려앉기·미끄러지기·사라지기·고리·반짝임 클래스
- 오목: 돌 내려앉기, 마지막 수 고리, 무르기 돌 사라짐, 승리 줄 차례로 반짝임, 금수 누르면 작은 소리, 돌 그림자
- 사목: 바닥에 닿아 한 번 튀기, 닿는 순간에 맞춘 "탁" 소리, 마지막 수 점은 닿은 뒤, 이긴 줄 차례로 깜빡임
- 오델로: 놓은 돌 먼저 내려앉고 뒤집기(들리며 뒤집힘), 뒤집힐 때마다 딸깍, 패스·무르기 소리, 마지막 수 고리
- 바둑: 돌 내려앉기, 따낸 돌 한 알씩 사라짐+딸깍, 패스 소리, 무르기 되돌림, 사석 표시 바뀜 소리
- 바둑 사석 확인 제한 시간에 무제한(0) 추가(기본 3분 그대로), 테스트·문서
- 숨은 탭 내 차례 소리는 방 화면이 이미 내므로 게임 쪽 중복 제거
- games E2E에 오목 기본 계획 추가

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 04:21:25 +09:00
EJClaw
bafbf95d98 할리갈리·도블·사과 게임: 뒤집기 시간 무제한·사과 게임 무제한(여기까지), 소리·움직임
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 04:16:54 +09:00
EJClaw
ec4c849096 방 막대: 320px 휴대폰에서도 버튼 7개가 한 줄에(소리 크기 추가 뒤 넘침), 휴대폰 소리 크기 창은 화면 오른쪽에 고정
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 04:15:42 +09:00
EJClaw
0a406306da 문서: 루미큐브·다빈치 코드·마작 무제한 시간 규칙
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 04:14:45 +09:00
EJClaw
f620faf70b 채팅 연속 입력 전부 전송(짧은 연타 허용 + 보내기 대기열), 사람도 '입력 중' 표시, 오른쪽 위 소리 크기(0~100, 기본 50)
- 서버 방 채팅: 0.5초 고정 간격 대신 토큰 버킷(4줄 연속, 초당 2줄) — 도배는 여전히 막음
- 웹: useChatOutbox(방 채팅·마피아·라이어 게임)로 빠르게 친 줄도 순서대로 전송
- typing 메시지(방 채팅 / 게임 공개 채팅만, 마피아 밤 채널은 보내지 않음), BotActivity에 사람 표시
- VolumeControl: 사이트 머리글·방 막대 오른쪽 위, 설정 페이지에도 슬라이더
- e2e/chat.e2e.ts: 연타 7줄, 입력 중, 소리 크기

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 04:14:19 +09:00
EJClaw
f053b8fc6b 루미큐브·다빈치 코드·마작 차례 시간 '무제한' 옵션: 무제한이면 타이머·시간 초과 없음(연결 끊김 처리는 그대로)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 04:10:35 +09:00
EJClaw
f12cf12b84 소리·애니메이션 공통 바탕: 사이트 음량(0~100, 기본 50, 이 기기만), 공통 효과음 sfx, 공통 움직임 클래스(anim-*)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 04:02:30 +09:00
EJClaw
544f704397 문서: 게임 33종(README), M10 새 게임 7개·윷놀이 지역 룰·채팅(로드맵), 새 게임 기본 규칙(결정 사항)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 03:58:57 +09:00
EJClaw
89312e28f2 윷놀이 지역 룰 옵션: 말 없을 때 빽도(버림·다시 던지기·날윷), 낙이면 차례 끝, 던진 순서대로, 업기 고르기, 갈림길 고르기
- 엔진: 새 옵션 5개(기본값은 예전 동작 그대로), MOVE에 piece·alt·stack(선택), 따로 선 무더기는 Piece.group으로 구분
- 컴퓨터: 다른 길·따로 두기·날윷 빽도를 점수로 판단, 따로 선 말도 함께 잡힐 위험으로 계산
- 화면: 방 설정 "지역 룰(우리 동네 규칙)" 묶음(빽도/말 움직이기/던지기, 고른 값 설명, 기본으로 되돌리기), 로비 요약·규칙 보기·도움말에 적용 중인 룰, 게임 중 갈 길 고르기·업기/따로 두기 버튼
- 문서: docs/games/yut.md 2장 표, 7장(추가한 룰·뺀 룰과 이유), 테스트·E2E 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 03:49:48 +09:00
EJClaw
71381087cc 야단법석 달리기(Magical Athlete): 규칙·컴퓨터 상대·화면·도움말·문서·E2E
- 규칙 모듈 packages/games/src/magical-athlete: 선수 24명(능력 처리 순서가 하나로 정해지는 선수만),
  뱀 순서 뽑기(2~3명은 선수 8명·경주마다 둘, 4~6명은 4명·하나), 몰래 동시에 출전 선수 고르기,
  경주 4번(순한 판·거친 판 번갈아, 거친 판은 화살표·돌·별 칸), 1등 3점·2등 1점(갈수록 커지는 점수표 옵션).
  능력 처리 순서 고정: 칸 효과 → 차례인 사람 → 시계 방향, 연쇄는 줄 끝, 선수당 한 차례 5번, 두 번째 도착 즉시 종료,
  경주 차례 상한. 시간 초과는 안전한 기본값(능력 안 씀), 나간 사람 선수는 자동으로 끝까지.
- 컴퓨터: 평가값 뽑기, 칸 수 기대 이득으로 능력 판단, 레벨별 실수.
- 화면: 뱀 모양 경주로 SVG(PC 11칸·휴대폰 8칸 줄), 말 이동 애니메이션, 능력 버튼, 경주 기록, 결과 표,
  도움말·30초 요약. 판이 화면보다 길면 위에서 시작(가운데 정렬이면 위가 잘려 고르기 카드를 못 누름).
- 등록(GAMES, CATALOG, BOT_GAMES, BOT_STRATEGIES, 화면 레지스트리, 아이콘·판 탭), 문서 docs/games/magical-athlete.md.
- 테스트: 규칙·능력·순서 42개(문서 예시 포함), 컴퓨터 10개, 도움말 2개, 방 통합 2개(컴퓨터 1·3명과 끝까지),
  E2E(PC 방장 + 휴대폰, 실제 뽑기·고르기·굴리기·능력으로 네 경주 끝까지).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 03:49:48 +09:00
EJClaw
65c56d3ae7 채팅: 가리기 삭제, 100줄이 찬 뒤에도 맨 아래 고정(+새 메시지 수), 이름 줄과 말풍선으로 이름·내용 구분
- 공통 ChatMessage(이름 줄 + 말풍선, 내 말은 오른쪽, 이어 말하면 이름 한 번) — 방 채팅·마피아·라이어 게임, 그림 맞히기 이름 표시
- useStickToBottom: 개수 대신 목록 내용 변화를 보고 맨 아래 유지, 위로 올려 읽는 중엔 그대로, 보내면 다시 맨 아래
- 휴대폰 채팅 버튼의 새 메시지 수도 100줄 뒤에 0이 되던 문제(마지막 본 id 기준으로)
- e2e/chat.e2e.ts: PC 대기실·게임 옆 칸·휴대폰 시트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 03:49:03 +09:00
EJClaw
115969515c E2E: 라이어 게임 병합 때 빠진 클루 도우미 함수의 닫는 괄호 복구
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 03:30:54 +09:00
EJClaw
74a7daa4d3 새 게임 라이어 게임: 규칙 엔진·말하는 컴퓨터·화면·도움말·문서·E2E
- packages/games/src/liar: 주제 10개 제시어 은행, 설명(두 번째 바퀴 거꾸로)·자유 토론·투표(동점 재투표 한 번, 또 동점이면 라이어 승리)·라이어 정답 맞히기(띄어쓰기·다른 표기 무시), 바보 모드
- 컴퓨터: 마피아처럼 live 전략, 레벨 1~60을 LiveBotInput.level 로 받음(서버 BotDriver 가 넘김), BOT_CHAT_REQUIRED 에 추가
- 웹: 꾹 누르는 제시어 카드, 설명 기록·토론 채팅·투표 화면, 30초 요약, [?] 도움말
- 문서 docs/games/liar.md, 등록(GAMES·CATALOG·BOT_GAMES·registry·아이콘), 서버 방 테스트, E2E(거절 알림이 저절로 사라지는지 확인 포함)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 03:17:14 +09:00
EJClaw
bde430f33e 새 게임 5개 병합 정리: 게임 고르기 탭·점수 없는 게임 목록 중복 정리, 도움말 개수 31
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 03:14:25 +09:00
EJClaw
609f458ed2 우노: 공식 규칙 엔진·컴퓨터 상대·화면·도움말·문서·E2E
- 규칙 모듈 packages/games/src/uno: 108장(원카드 색깔 카드 덱·점수 재사용, 원카드 코드는 그대로),
  7장씩, 공식 시작 카드 처리(드로우4 다시 섞기, 드로우2·스킵·리버스, 와일드는 첫 사람이 색 고르기),
  색·숫자·기호 맞추기, 낼 카드가 있어도 뽑기 + 뽑은 카드 바로 내기, 2명 리버스=스킵,
  와일드 드로우4 도전(공식: 몰래 낼 수 있고 성공 4장/실패 6장, 손패는 도전한 사람만) 또는 쉬운 규칙,
  "우노!" 외치기(내면서 또는 직후, 다음 차례 행동 전까지 누구나 잡기 2장), 공식 점수(한 판/500점),
  하우스 룰(드로우 카드 쌓기, 낼 수 있을 때까지 뽑기, 기본 끄기). 시간 초과는 낼 수 있는 카드 자동
  (와일드는 많이 가진 색), 나가기·자리 비움 처리.
- 컴퓨터 상대(bot.ts): 레벨별 우노 깜빡함·잡기 확률, 드로우 카드 아끼기, 드로우4 거짓말/도전 판단, 색 고르기.
- 테스트: 규칙 시나리오, 무작위 대국(유출·보존·결정성), 컴퓨터, 방에서 사람 1 + 컴퓨터 3 끝까지.
- 화면 apps/web/src/games/uno: 지금 색 링·칩, 방향·다음 사람, 남은 장수, 우노 버튼(준비/외치기),
  잡기 버튼, 도전·시작 색·판 결과 창, 30초 요약, 지금 할 수 있는 것.
- 등록(GAMES, 카탈로그, BOT_GAMES/BOT_STRATEGIES, 화면 레지스트리, 아이콘·카드 탭), docs/games/uno.md,
  E2E 계획(PC 1 + 휴대폰 2, 끝까지, 잡기·도전 화면).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 03:09:33 +09:00
EJClaw
cf7523f862 도둑잡기(old-maid): 규칙·화면·컴퓨터 상대·테스트·문서·E2E
- 규칙 모듈 packages/games/src/old-maid: 2~8명, 트럼프 52장 + 조커 1장을 첫 사람(무작위)부터
  한 장씩 나누고 같은 숫자 짝은 자동으로 버림. 차례에는 다음 자리(왼쪽)의 카드 있는 사람
  손패에서 자리(index)로 한 장 뽑기(from 함께 보내 대상이 바뀌면 거절), 짝이 없으면 내 손패
  무작위 자리에 숨김. 다 턴 순서대로 순위, 마지막 조커를 든 사람이 도둑(꼴찌).
  결과 scoreText 에 "🃏 도둑"/"다 털었어요"/"나감" 표시.
- 내 손패 섞기: 남은 사람 누구나 언제든, 차례마다 3번까지, 시계는 그대로. 남에게 보이는 자리는
  실제 손패 순서이고, view 에는 남의 손패 장수만(뽑은 카드는 뽑은 사람에게만).
- 시간 초과는 무작위 한 장 뽑기(3번 연속이면 5초), 카드를 든 채 나가면 그 카드를 섞어 다음
  자리부터 한 장씩 나눠 주고 짝을 버림, 나간 사람은 맨 아래. 둘만 남았을 때 나가면 도둑 없이 끝.
- 컴퓨터 상대(BOT_GAMES): 단계와 관계없이 무작위로 뽑고 가끔(15%) 자기 손패를 먼저 섞음.
- 화면 apps/web/src/games/old-maid: 뽑힐 사람의 뒷면 카드를 펼쳐 고르기(tapConfirm 이면 두 번
  눌러 확인, PC 한 번, 키보드 방향키+Enter), 섞으면 흔들림, 지난 뽑기·버린 짝, 내 손패(조커 표시)와
  [🔀 섞기], 조커를 넘기면 알림. 30초 요약, 지금 할 수 있는 것, 규칙.
- 등록(GAMES, 카탈로그, BOT_GAMES·전략, 화면 레지스트리, 아이콘·카드 탭), 도움말 테스트 게임 수 27,
  문서 docs/games/old-maid.md, E2E 계획(PC 1 + 휴대폰 2, 끝까지).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 03:09:33 +09:00
EJClaw
3fffcec52b 커넥트 포(사목) 규칙·컴퓨터 상대·화면·테스트
- 규칙 모듈 packages/games/src/connect-four: 7×6 기본, 8×7·9×7 판, 열을 고르면 맨 아래 빈칸으로
  떨어짐, 가로·세로·대각선 4개(이상) 즉시 승리(이긴 줄 전부 기록), 판이 차면 무승부. 먼저 두는 사람은
  오목·오셀로와 같은 관례(무작위/방장 먼저/방장 나중/판마다 번갈아 — gameNo). 시간: 한 수당·피셔·없음,
  시간 초과 자동 두기(승리 > 막기 > 위 칸을 내주지 않는 가운데 열), 허용 횟수 넘으면 시간패, 기권·나가기.
- 컴퓨터 상대: 네가맥스 알파베타 + 반복 심화 + 치환표, 바로 이기기/막기·강제 수 판정, 열린 줄과 홀짝 줄
  위협을 증분 평가. 레벨 1~60에 따라 1~10수 읽기(어려움은 빈칸 24개부터 끝까지 시도), 국면 5만 개 상한으로
  한 수 평균 수 ms·최악 수십 ms. humanBest로 사람 같은 실수, 낮은 단계는 4목 막기를 가끔 놓침.
- 화면 apps/web/src/games/connect-four: 구멍 뚫린 파란 판(마스크), 떨어지는 애니메이션(움직임 줄이기
  존중), 이긴 줄 강조, 열 전체 터치 영역, 키보드 ←·→·Home·End·Enter, 스크린리더 안내, 다크 모드,
  30초 요약·도움말.
- 등록: GAMES, CATALOG, BOT_GAMES, BOT_STRATEGIES, NO_LUCK, 화면 레지스트리, 아이콘·판 탭, 공통 테스트 목록.
- 문서 docs/games/connect-four.md, 목록 한 줄. E2E 계획(PC 키보드 + 휴대폰 터치, 꽉 찬 열 무시, 끝까지).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 03:09:33 +09:00
EJClaw
c9f81804cf 클루: 규칙·컴퓨터 상대·화면·테스트
- 규칙 모듈 packages/games/src/clue: 3~6명, 용의자 6·흉기 6·방 9, 봉투 3장, 나머지는 같은 장수로
  나누고 남는 카드는 공개(원작). 9개 방 + 복도를 거리 표로 단순화한 저택(비밀 통로 부엌↔서재,
  온실↔라운지), 주사위 2개 합만큼 이동해 닿는 방에 들어가거나 먼 방 쪽으로 걸어가기, 빠른 이동 옵션.
  추리 시 용의자 말·흉기 이동과 불려 온 사람의 제자리 추리, 다음 사람부터 반증(반증자가 직접 고름,
  보여 준 카드는 두 사람만), 고발(틀리면 탈락하되 반증은 계속, 모두 틀리면 무승부).
  카드 id(card-*)와 추리 이름을 나눠 view 누출 검사가 의미 있게, 이벤트에는 카드 없음.
  시간 초과는 차례를 통째로 자동 진행, 반증은 첫 카드 자동, 나가면 카드 공개.
- 컴퓨터 상대(bot.ts): 소거 노트(내 카드·공개·받은 카드 → 못 보여 준 사람·손패 수 → "셋 중 하나"
  제약·틀린 고발), 단계가 높을수록 깊게, 확실할 때만 고발, 모르는 카드로 추리, 모르는 방으로 이동.
- 화면 apps/web/src/games/clue: 저택 지도(말·흉기·거리·통로), 주사위·방 고르기, 추리/고발 칩,
  반증 카드 고르기, 내 카드·공개 카드, 추리 노트(localStorage, 방 코드+게임 번호), 추리 기록.
- 등록(GAMES, 카탈로그, BOT_GAMES, BOT_STRATEGIES, 화면 레지스트리, 아이콘·분류), 문서
  docs/games/clue.md, E2E 계획(PC 1 + 휴대폰 2, 끝까지).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 03:09:33 +09:00
EJClaw
b98775b0a6 사과 게임: 같은 판(17×10) 합 10 만들기 경주, 1~8명·혼자 가능, 레벨별 컴퓨터(라이브 봇)
- 규칙 모듈 packages/games/src/apple: 시드로 만든 한 판(1~9, 합 10의 배수)을 모두 각자 풀고,
  직사각형 합이 딱 10이면 지운 개수만큼 점수. 빈 칸은 합에 영향 없음, 합≠10·빈 직사각형은 거절(벌점 없음).
  3초 카운트다운(판 숨김) → 제한 시간 1/2/3분(기본 2분), 서버 시계 마감(deadline = timeoutNotBefore,
  끊긴 사람 조기 시간 초과 없음), 1초 5번 속도 제한, 더 지울 게 없으면 막힘 → 모두 막히면 조기 종료,
  나가면 맨 아래 순위·혼자 남으면 끝. 동점은 같은 순위, 결과 "사과 N개".
- view는 내 판(170자 문자열)과 모두의 점수만(남의 판 없음). findMoves는 누적합으로 가장 좁은 합 10 직사각형 전부.
- 컴퓨터: 마피아처럼 LIVE_BOT_STRATEGIES.apple. live 전략에 level 전달(서버 bots.ts, live-playout).
  레벨 따라 찾는 시간(6초→2초)·시야·놓침(쉬움 30%)·고르기가 달라짐. 2분 평균 레벨1 약 28개 ~ 레벨60 약 99개.
- 화면 apps/web/src/games/apple: SVG 사과, 포인터 드래그(마우스·터치), 합계 실시간·10이면 초록,
  낙관적 지우기와 튀어 오르는 애니메이션, 휴대폰은 판을 돌려 10열×17줄, 키보드(화살표+스페이스 두 번, Esc),
  다른 사람 점수 칩, 다크 모드, 도움말·30초 요약.
- 등록(GAMES, CATALOG, BOT_GAMES, 화면 레지스트리, 아이콘·파티 탭), 문서 docs/games/apple.md, 09 §9 라이브 봇 줄.
- 테스트: 규칙 15개(무차별 대조, 무작위 대국 1·2·5·8명), 컴퓨터 5개, 도움말 2개, 방 통합 2개(컴퓨터와 끝까지),
  E2E(PC 마우스·키보드, 휴대폰 CDP 터치, 320px, 1분 뒤 결과).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 22:20:49 +09:00
EJClaw
2ec622ebf6 방 설정 "컴퓨터 채팅": 컴퓨터가 혼자 말하는 건 방장이 켤 때만(기본 끄기), 마피아는 항상 켜짐
- RoomConfig/RoomView.botChat, config 메시지에 botChat. 새 방·옛 방 모두 끄기.
- BotBrain: 꺼져 있으면 도발·반응·대답·시작 인사·끝 인사 안 함, 모델 미리 올리기도 안 함.
  바퀴벌레 포커 진짜/블러핑 판단은 그대로, 한마디만 뺌.
- BOT_CHAT_REQUIRED(마피아): 설정과 상관없이 항상 켜짐, 설정 칸에 "항상 켜짐" 표시.
- 대기실 설정에 컴퓨터 채팅 켜기/끄기(컴퓨터 상대가 있는 게임만).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 21:59:30 +09:00
EJClaw
bd179c7a43 보고서: 텀블링 몽키 3D 물리 간이 실험 스크립트·결과, 설계 문서 근거 연결
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 23:21:00 +09:00
EJClaw
2fe43952d3 문서: 텀블링 몽키 진짜 3D 설계(서버 Rapier 결정적 물리 + three.js)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 23:19:28 +09:00
EJClaw
84d64b27f2 컴퓨터 난이도 1~60단계·방장 선택·판마다 변화·운, 공정성 확인에 표기, 업데이트 알림 팝업
- 난이도 1~60(쉬움 1~20·보통 21~40·어려움 41~60): 넣을 때 랜덤, 방장이 대기실에서 [랜덤][쉬움][보통][어려움] 선택(botLevel) → 범위 안 무작위
- 다음 판마다 -2~+2, 처음 단계 ±5·같은 범위 안(drift); 말투는 처음 단계(>30 존댓말)
- humanBest 확률을 단계별로 보간(BOT_PLAY_ANCHORS: 1·10·30·50·60)
- 운(-1~+1): 카드·주사위 게임에서 시작 전에 시드 후보 1~5개를 작업 스레드에서 끝까지 둬 보고 운에 맞는 것을 고름(luck.ts, luck-worker.ts). 해시 공개는 그대로
- 결과 화면 공정성 확인에 컴퓨터별 단계·운, 섞어 본 후보 수
- 업데이트 알림: 빌드 ID meta + /api/version + welcome.build → 상단 팝업 [지금 새로고침하기] [✕]
- 문서 03·04 §5.1·06 §12·07 §11.1·09 §9.1, 테스트(bot-level.room, luck, version, e2e bots·pwa)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 17:46:13 +09:00
EJClaw
3cbc3698d3 컴퓨터 난이도(쉬움 35%·보통 40%·어려움 25%)와 사람 같은 수, 서버 난수를 OS 보안 난수로
- secureRandom(): crypto.getRandomValues 53비트 실수. 서버의 Math.random(컴퓨터 수·생각 시간·AI 말·방 코드·마감 유예)을 모두 교체
- 컴퓨터 id의 ULID를 secureRandom으로 만들고, 그 무작위 부분 30비트로 난이도·말투(smart)를 정함(botDraw)
- humanBest: 오목·체스·장기·오델로·바둑에서 난이도별로 비슷한 수(slip)·사고(lapse)·꼭 둬야 할 수 놓침(miss)
- 문서 09 §9.1(확률표·게임별 기준·대국 결과), 06 §12; 테스트 bots/level.test.ts, 레벨별 완주 테스트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:19:06 +09:00
EJClaw
07fe46562f 보고서: AI·GPU 이전·다시 보기 결과(docs/reports/ai-gpu-20261011.md)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 03:49:56 +09:00
EJClaw
5f60ad1dd4 마피아: 직업 대답(시민이에요)은 정해 둔 문장 그대로
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 03:47:50 +09:00
EJClaw
119d10fac6 AI: 게임 시작 때 모델 미리 올리기, 2시간 유지
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 03:40:08 +09:00
EJClaw
c7dab689ca 배포: .9 GPU 호스트용 compose(docker-compose.ai.yml), 문서 06 §12.1·11 §8·마피아 §13
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 03:38:05 +09:00
EJClaw
13974181e7 컴퓨터 플레이어 + GPU 로컬 모델(gemma3:4b): 생각 중/입력 중 표시, 성격대로 채팅·도발·심리전, 바퀴벌레 포커 블러핑, 마피아 대사
- ai/llm.ts: Ollama 클라이언트(동시 2개·대기열·시간 제한·연속 실패 시 쉬기), 꺼져 있으면 예전처럼 조용히 둔다
- ai/lines.ts: 성격 5가지(도발·허세·차분·수다·소심)×말투(존댓말/반말), 한 줄 정리(외국어·AI 말·욕·링크 거르기)
- ai/brain.ts: 수 두기 전 생각 중… → 가끔 입력 중…(타자 시간) → 채팅 → 수, 사람 수에 반응, 이름 부르면 대답, 시작·끝 한마디
  바퀴벌레 포커: 진실/블러핑과 건네는 말을 모델이 정함. 마피아: 계획한 대사를 모델이 자기 말로(직업 주장은 버림)
- RoomView.botActivity + 화면 표시(상태 줄, 채팅 칸), AI_URL/AI_MODEL 설정, /healthz에 ai 통계
- 테스트: 클라이언트·정리·방 동작(가짜 모델), 실제 GPU 모델 브라우저 E2E(e2e/ai.e2e.ts)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 03:37:04 +09:00
EJClaw
65a0f34d93 다시 보기: 컴퓨터와 한 판·점수 문구 이전 게임도 다시 볼 수 있게(결과 비교를 순위·점수·이유·요약으로)
운영 DB 44판 중 21판이 '다시 볼 수 없어요'였던 원인: 저장 결과의 practice 표시와 새 scoreText 때문에 JSON 전체 비교가 실패.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 03:18:54 +09:00
724 changed files with 116398 additions and 4182 deletions

View File

@@ -5,23 +5,25 @@
운영 중: https://game.tkrmagid.kr
## 게임 (26개)
## 게임 (46개)
| 종류 | 게임 |
|---|---|
| 2인 수 싸움 | 오목, 오셀로, 체스(체스960 포함), 장기, 바둑, 쿼리도(2·4명) |
| 카드·화투 | 원카드, 섯다, 포커, 고스톱, 달무티, 구십구, 바퀴벌레 포커, 뱅! |
| 타일·주사위 | 루미큐브, 다빈치 코드, 마작, 요트 다이스, 윷놀이, 라스베가스, 부루마불, 스플렌더 |
| 순발력·대화 | 할리갈리, 도블, 그림 맞히기, 마피아 |
| 2인 수 싸움 | 오목, 커넥트 포(사목), 오셀로, 체스(체스960 포함), 장기, 바둑, 쿼리도(2·4명) |
| 카드·화투 | 원카드, 우노, 도둑잡기, 섯다, 포커, 블랙잭, 고스톱, 달무티, 티츄, 젝스님트, 구십구, 바퀴벌레 포커, 뱅! |
| 타일·주사위·판 | 루미큐브, 다빈치 코드, 마작, 요트 다이스, 윷놀이(지역 룰 선택, 증강 윷놀이), 라스베가스, 부루마불, 스플렌더, 야단법석 달리기, 클루, 젬블로, 버건디의 성 |
| 혼자·퍼즐(같은 판 경주) | 지뢰찾기, 사천성, 솔리테어(클론다이크·프리셀·스파이더), 스도쿠, 네모네모 로직 |
| 순발력·대화·파티 | 할리갈리, 도블, 그림 맞히기, 사과 게임, 타자 대결, 마피아, 라이어 게임, 핫스트릭, 사건 파일(협력 추리) |
칩·포인트·지폐는 모두 놀이용이다(실제 돈과 무관).
칩·포인트·지폐, 섯다의 "원"은 모두 놀이용이다(실제 돈과 무관, 충전·환전 없음).
## 주요 기능
- 로그인: 디스코드 또는 게스트(닉네임만). 게스트는 로그아웃하거나 하루 동안 접속하지 않으면 계정이 지워진다.
- 방: 방 링크를 보내면 친구가 바로 들어온다. 방 막대에서 링크 복사·채팅·규칙·설정(글자 크기·소리)·나가기를 한 번에 누른다. 게임 중에 나가면 기권으로 처리된다.
- 컴퓨터 상대: 실시간·대화 게임(할리갈리, 도블, 그림 맞히기, 마피아)을 뺀 22개 게임.
- 모든 게임에 효과음과 움직임(상대·컴퓨터의 수에도 나옴), 오른쪽 위 소리 크기(0~100, 기본 50). 시간 제한이 있는 게임은 모두 "무제한"도 고를 수 있다.
- 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)과 협력 추리(사건 파일)를 뺀 42개 게임. 마피아·라이어 게임의 컴퓨터는 채팅으로 말하고, 다른 게임의 컴퓨터 잡담은 방장이 켤 때만.
- 처음 하는 사람을 위한 30초 규칙 요약, 게임별 규칙 페이지, 끝난 판 다시 보기, 이름을 누르면 나오는 기록 카드.
- 홈 화면에 추가(PWA), 휴대폰(320px부터)·PC, 다크 모드.
- 관리자 화면(`/admin`): 게임 규칙 기본값·잠금, 사용자·방 관리, 계정별 기록.
- 관리자 화면(`/admin`): 게임 규칙 기본값·잠금, 라이어 게임 주제·제시어 추가/수정/삭제, 게임 속도 배율(애니메이션·컴퓨터 생각 시간, 1/16~16배), 사용자·방 관리, 계정별 기록.
## 개발
```bash
@@ -47,6 +49,9 @@ bun e2e/pwa.e2e.ts # PWA: 매니페스트·아이콘, 서비스
bun e2e/bots.e2e.ts # 컴퓨터 상대, 방 나가기, 게스트 로그아웃
bun e2e/replay.e2e.ts # 다시 보기
bun e2e/tutorial.e2e.ts # 처음 하는 사람용 규칙 요약
bun e2e/speed.e2e.ts # 게임 속도 배율: 판 애니메이션 재생 속도와 컴퓨터 응답 시간
bun e2e/settings.e2e.ts # 설정 팝업: 게임 중에 열어도 방에서 나가지 않음, 바로 적용, 닫기·포커스
bun e2e/room-back.e2e.ts # 혼자인 대기실에서 뒤로가기 → 빈 방 바로 닫힘, 친구가 있으면 자리 유지, 규칙 팝업
bun scripts/loadtest.ts --help # 부하·장애 주입 (docs/reports 참고)
```

View File

@@ -2,6 +2,8 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { Client, TEST_SUPERADMINS, api, boot, guest, sleep } from './test-utils';
import { GUEST_IDLE_MS } from './server';
import { TOPICS, bankTopics, liarBankRef, setLiarBank, setLiarBankResolver, type LiarState } from '@bg/games/liar';
import type { Conn, Room } from './rooms/room';
const [SUPER, SUPER2] = TEST_SUPERADMINS;
type Booted = ReturnType<typeof boot>;
@@ -11,6 +13,9 @@ const clients: Client[] = [];
afterEach(async () => {
for (const c of clients.splice(0)) c.close();
for (const s of running.splice(0)) await s.stop();
// The 라이어 word bank is process-wide (the game module holds it): back to the code's for the next test.
setLiarBank(TOPICS, null);
setLiarBankResolver(null);
});
function start(): Booted {
@@ -142,6 +147,109 @@ describe('game settings', () => {
});
});
describe('라이어 게임 제시어 (§4.1)', () => {
const topic = {
ko: '우리 반',
generic: ['교실에 있어요', '매일 봐요'],
words: [
{ word: '칠판', hints: ['앞에 걸려 있어요', '분필로 써요'], aliases: ['흑판'], group: '앞' },
{ word: '교탁', hints: ['선생님 자리예요'], group: '앞' },
{ word: '사물함', hints: ['뒤에 있어요', '자물쇠를 달아요'], group: '뒤' },
{ word: '청소함', hints: ['빗자루가 들어 있어요'], group: '뒤' },
],
};
const send = (s: Booted, cookie: string, method: string, path: string, body?: unknown) =>
api(s.base, `/api/admin/liar${path}`, { method, cookie, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
test('추가·수정·삭제·되돌리기, 잘못된 단어는 이유와 함께 거절, 일반 사용자는 403, 모두 기록', async () => {
const s = start();
const sup = await discordLogin(s, SUPER);
const plain = await discordLogin(s, '111111111111111111');
expect((await send(s, plain.cookie, 'GET', '/topics')).res.status).toBe(403);
expect((await send(s, plain.cookie, 'POST', '/topics', topic)).res.status).toBe(403);
const list = await send(s, sup.cookie, 'GET', '/topics');
expect(list.body.topics.map((t: any) => t.id)).toEqual(TOPICS.map((t) => t.id));
expect(list.body.topics[0]).toMatchObject({ id: 'fruit', builtin: true, modified: false, deleted: false });
expect(list.body.topics[0].words[0].group).toBeTruthy();
// Problems come back in Korean: the word inside its own hint, and one word inside another.
const bad = await send(s, sup.cookie, 'POST', '/topics', { ...topic, words: [...topic.words, { word: '큰칠판', hints: ['큰 칠판이에요'] }] });
expect(bad.res.status).toBe(400);
expect(bad.body.error).toContain("'큰칠판'의 설명");
expect(bad.body.error).toContain("'칠판'가 '큰칠판' 안에");
const made = await send(s, sup.cookie, 'POST', '/topics', topic);
expect(made.res.status).toBe(200);
const id = made.body.topic.id as string;
expect(id).toMatch(/^c_[a-z0-9]+$/);
expect(made.body.topic).toMatchObject({ ko: '우리 반', builtin: false, deleted: false });
expect((await api(s.base, '/api/liar/topics')).body.topics.at(-1)).toEqual({ id, ko: '우리 반', words: 4 });
// Edit a built-in topic (drop 수박), then reset it.
const fruit = list.body.topics[0];
const edited = await send(s, sup.cookie, 'PUT', '/topics/fruit', { ko: fruit.ko, generic: fruit.generic, words: fruit.words.filter((w: any) => w.word !== '수박') });
expect(edited.res.status).toBe(200);
expect(edited.body.topic).toMatchObject({ builtin: true, modified: true });
expect(bankTopics(liarBankRef()).find((t) => t.id === 'fruit')!.words.some((w) => w.word === '수박')).toBe(false);
expect((await send(s, sup.cookie, 'POST', '/topics/fruit/reset')).body.topic.modified).toBe(false);
expect(bankTopics(liarBankRef()).find((t) => t.id === 'fruit')!.words.some((w) => w.word === '수박')).toBe(true);
// Delete: a built-in topic is hidden (and can come back), an admin's own is gone.
expect((await send(s, sup.cookie, 'DELETE', '/topics/person')).res.status).toBe(200);
expect((await api(s.base, '/api/liar/topics')).body.topics.some((t: any) => t.id === 'person')).toBe(false);
expect((await send(s, sup.cookie, 'GET', '/topics')).body.topics.find((t: any) => t.id === 'person')).toMatchObject({ deleted: true });
await send(s, sup.cookie, 'POST', '/topics/person/reset');
expect((await api(s.base, '/api/liar/topics')).body.topics.some((t: any) => t.id === 'person')).toBe(true);
expect((await send(s, sup.cookie, 'DELETE', `/topics/${id}`)).res.status).toBe(200);
expect((await send(s, sup.cookie, 'PUT', `/topics/${id}`, topic)).res.status).toBe(404);
expect(liarBankRef()).toBeNull();
const audit = await api(s.base, '/api/admin/audit', { cookie: sup.cookie });
expect(audit.body.entries.map((e: any) => e.action)).toEqual(['liar.topic.delete', 'liar.topic.reset', 'liar.topic.delete', 'liar.topic.reset', 'liar.topic.update', 'liar.topic.create']);
});
test('새 판은 고친 은행을 쓰고 그 판본을 옵션에 남겨요. 은행을 또 고쳐도 지난 판본은 남고, 서버를 다시 켜도 그대로', async () => {
const s = start();
const sup = await discordLogin(s, SUPER);
const id = (await send(s, sup.cookie, 'POST', '/topics', topic)).body.topic.id as string;
const ref = liarBankRef()!;
expect(ref).toBeTruthy();
const host = await guest(s.base, '방장');
const room = s.rooms.createPractice(host.id, 'liar') as Room;
const conn: Conn = { userId: host.id, send: () => {}, close: () => {} };
room.join(conn, 'player');
expect(room.configure(host.id, { options: { ...(room.config.options as object), topic: id, foolMode: true } })).toBeNull();
expect(room.start(host.id)).toBeNull();
for (let i = 0; i < 200 && !room.game; i++) await sleep(10);
const st = room.game!.state as LiarState;
expect(st.topic).toBe(id);
expect(st.options.bank).toBe(ref);
expect(st.words).toEqual(['칠판', '교탁', '사물함', '청소함']);
// 바보 모드: the liar's word is from the same group.
const group = (w: string) => topic.words.find((x) => x.word === w)!.group;
expect(group(st.liarWord!)).toBe(group(st.word));
const stored = s.db.query<{ options_json: string }, []>("SELECT options_json FROM games WHERE game_id = 'liar'").get()!;
expect(JSON.parse(stored.options_json).bank).toBe(ref);
// Another change: a new version; the old one is still found (replays).
await send(s, sup.cookie, 'PUT', `/topics/${id}`, { ...topic, words: topic.words.slice(0, 2) });
expect(liarBankRef()).not.toBe(ref);
expect(bankTopics(ref).find((t) => t.id === id)!.words).toHaveLength(4);
expect(bankTopics(liarBankRef()).find((t) => t.id === id)!.words).toHaveLength(2);
// Restart on the same database: same bank, same version name.
const now = liarBankRef();
await s.stop();
running.splice(running.indexOf(s), 1);
setLiarBank(TOPICS, null);
const again = boot(s.dbPath);
running.push(again);
expect(liarBankRef()).toBe(now);
expect(bankTopics(ref).find((t) => t.id === id)!.words).toHaveLength(4);
});
});
describe('admin-only options (threat guides)', () => {
test('off by default; the host cannot turn them on; the admin default always wins and is not shown as a lock', async () => {
const s = start();
@@ -196,6 +304,59 @@ describe('site settings, rooms, users', () => {
expect((await chat).text).toBe('너 **야');
});
test('game speed: 1/16~16 (default 1), shown in /api/config, out of range rejected', async () => {
const s = start();
const sup = await discordLogin(s, SUPER);
const site = (await api(s.base, '/api/admin/site', { cookie: sup.cookie })).body.site;
expect(site.gameSpeed).toBe(1);
expect((await api(s.base, '/api/config')).body.gameSpeed).toBe(1);
for (const bad of [0, 1 / 32, 17, -1]) {
const r = await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, gameSpeed: bad }) });
expect(r.res.status).toBe(400);
}
for (const ok of [1 / 16, 16, 0.75]) {
const r = await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, gameSpeed: ok }) });
expect(r.res.status).toBe(200);
expect((await api(s.base, '/api/config')).body.gameSpeed).toBe(ok);
}
// An open room gets the new speed at once (its screen's animations follow it).
const g = await guest(s.base, '방장님');
const room = await api(s.base, '/api/rooms', { method: 'POST', cookie: g.cookie, body: JSON.stringify({ gameId: 'omok' }) });
const c = await new Client(s.base, g.cookie, g.id).connect();
clients.push(c);
c.send({ t: 'join', code: room.body.code, as: 'player' });
expect((await c.next('room')).room.gameSpeed).toBe(0.75);
const next = c.next('room');
await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, gameSpeed: 2 }) });
expect((await next).room.gameSpeed).toBe(2);
});
test('chat sound: 0~200% (default 80), shown in /api/config and open rooms, out of range rejected', async () => {
const s = start();
const sup = await discordLogin(s, SUPER);
const site = (await api(s.base, '/api/admin/site', { cookie: sup.cookie })).body.site;
expect(site.chatSound).toBe(80);
expect((await api(s.base, '/api/config')).body.chatSound).toBe(80);
for (const bad of [-1, 201, 50.5]) {
const r = await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, chatSound: bad }) });
expect(r.res.status).toBe(400);
}
for (const ok of [0, 200, 120]) {
const r = await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, chatSound: ok }) });
expect(r.res.status).toBe(200);
expect((await api(s.base, '/api/config')).body.chatSound).toBe(ok);
}
const g = await guest(s.base, '방장님');
const room = await api(s.base, '/api/rooms', { method: 'POST', cookie: g.cookie, body: JSON.stringify({ gameId: 'omok' }) });
const c = await new Client(s.base, g.cookie, g.id).connect();
clients.push(c);
c.send({ t: 'join', code: room.body.code, as: 'player' });
expect((await c.next('room')).room.chatSound).toBe(120);
const next = c.next('room');
await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, chatSound: 30 }) });
expect((await next).room.chatSound).toBe(30);
});
test('admin closes a room: everyone is told and disconnected from it', async () => {
const s = start();
const sup = await discordLogin(s, SUPER);

View File

@@ -0,0 +1,153 @@
/**
* 라이어 게임 제시어 관리 (docs/games/liar.md §3.1, docs/14-admin.md §4.1): admins replace, delete or add whole topics.
* The changes live in `liar_topics`; the merged bank is handed to the game module (`setLiarBank`) with a version name
* (hash of the changes) that new games carry in their options. Every version is kept in `liar_bank_versions` so a replay
* (or a game restored after a restart) sets up from the bank it started with.
*/
import type { Database } from 'bun:sqlite';
import { z } from 'zod';
import { TOPICS, mergeBank, setLiarBank, setLiarBankResolver, topicProblems, type LiarTopic, type TopicOverride } from '@bg/games/liar';
import { sha256Hex } from '../auth/sessions';
const line = (max: number) => z.string().trim().min(1).max(max);
export const LiarTopicInputSchema = z.object({
ko: line(20),
generic: z.array(line(80)).max(20),
words: z
.array(
z.object({
word: line(20),
aliases: z.array(line(20)).max(10).optional(),
hints: z.array(line(80)).max(10),
group: z.string().trim().max(20).optional(),
}),
)
.max(300),
});
export type LiarTopicInput = z.infer<typeof LiarTopicInputSchema>;
/** Most topics an admin may add. */
export const CUSTOM_TOPICS_MAX = 100;
export interface AdminLiarTopic extends Omit<LiarTopic, 'groups'> {
builtin: boolean;
/** Built-in topic changed by an admin (can be reset). */
modified: boolean;
/** Built-in topic an admin deleted (can be restored). */
deleted: boolean;
}
/** Drops empty optional fields so the stored JSON stays small and stable. */
function clean(t: LiarTopicInput): NonNullable<TopicOverride['topic']> {
return {
ko: t.ko,
generic: t.generic,
words: t.words.map((x) => ({
word: x.word,
hints: x.hints,
...(x.aliases?.length ? { aliases: x.aliases } : {}),
...(x.group ? { group: x.group } : {}),
})),
};
}
export class LiarBankStore {
private rows: TopicOverride[] = [];
private versions = new Map<string, readonly LiarTopic[]>();
constructor(private db: Database) {
this.load();
setLiarBankResolver((ref) => this.version(ref));
}
private load(): void {
this.rows = this.db
.query<{ id: string; json: string }, []>('SELECT id, json FROM liar_topics ORDER BY created_at, id')
.all()
.map((r) => ({ id: r.id, ...(JSON.parse(r.json) as Omit<TopicOverride, 'id'>) }));
const ref = this.rows.length ? sha256Hex(JSON.stringify(this.rows)).slice(0, 16) : null;
const topics = mergeBank(this.rows);
if (ref) {
this.db.query('INSERT OR IGNORE INTO liar_bank_versions (ref, json, created_at) VALUES (?, ?, ?)').run(ref, JSON.stringify(this.rows), Date.now());
this.versions.set(ref, topics);
}
setLiarBank(topics, ref);
}
/** A stored bank version (null if unknown: the game falls back to the bank in the code). */
private version(ref: string): readonly LiarTopic[] | null {
const hit = this.versions.get(ref);
if (hit) return hit;
const row = this.db.query<{ json: string }, [string]>('SELECT json FROM liar_bank_versions WHERE ref = ?').get(ref);
if (!row) return null;
const topics = mergeBank(JSON.parse(row.json) as TopicOverride[]);
if (this.versions.size > 50) this.versions.clear();
this.versions.set(ref, topics);
return topics;
}
/** Every topic for the admin screen: the bank in use (code order, then the admins' own), then deleted built-in ones. */
list(): AdminLiarTopic[] {
const by = new Map(this.rows.map((r) => [r.id, r]));
const out: AdminLiarTopic[] = mergeBank(this.rows).map((t) => {
const builtin = TOPICS.some((b) => b.id === t.id);
return { id: t.id, ko: t.ko, generic: t.generic, words: t.words, builtin, modified: builtin && !!by.get(t.id)?.topic, deleted: false };
});
for (const b of TOPICS) if (by.get(b.id)?.deleted) out.push({ id: b.id, ko: b.ko, generic: b.generic, words: b.words, builtin: true, modified: false, deleted: true });
return out;
}
get(id: string): AdminLiarTopic | null {
return this.list().find((t) => t.id === id) ?? null;
}
/** Problems (Korean) with a topic as typed, or none. */
problems(t: LiarTopicInput): string[] {
return topicProblems(clean(t));
}
private write(id: string, value: Omit<TopicOverride, 'id'>, by: string, now: number): void {
this.db
.query(
'INSERT INTO liar_topics (id, json, created_at, updated_by, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET json = excluded.json, updated_by = excluded.updated_by, updated_at = excluded.updated_at',
)
.run(id, JSON.stringify(value), now, by, now);
this.load();
}
private remove(id: string): void {
this.db.query('DELETE FROM liar_topics WHERE id = ?').run(id);
this.load();
}
/** Replaces a topic (built-in or the admins' own, also a deleted built-in one: that restores it). Validate first. */
save(id: string, t: LiarTopicInput, by: string, now = Date.now()): void {
this.write(id, { topic: clean(t) }, by, now);
}
/** Adds a topic of the admins' own; returns its id, or null when there are too many. */
create(t: LiarTopicInput, by: string, now = Date.now()): string | null {
if (this.rows.filter((r) => !TOPICS.some((b) => b.id === r.id)).length >= CUSTOM_TOPICS_MAX) return null;
let id: string;
do id = `c_${now.toString(36)}${Math.floor(Math.random() * 36 ** 3).toString(36)}`;
while (this.rows.some((r) => r.id === id));
this.write(id, { topic: clean(t) }, by, now);
return id;
}
/** Deletes a topic: a built-in one is hidden (can be restored), an admin's own is gone. */
delete(id: string, by: string, now = Date.now()): void {
if (TOPICS.some((b) => b.id === id)) this.write(id, { deleted: true }, by, now);
else this.remove(id);
}
/** A built-in topic back to the code's words (undoes a change or a delete). */
reset(id: string): void {
this.remove(id);
}
/** Topics new rooms can pick, for the lobby. */
static choices(topics: readonly LiarTopic[]): { id: string; ko: string; words: number }[] {
return topics.map((t) => ({ id: t.id, ko: t.ko, words: t.words.length }));
}
}

View File

@@ -5,7 +5,7 @@
import type { Database } from 'bun:sqlite';
import { z } from 'zod';
import type { AnyGameDefinition } from '@bg/engine';
import { CATALOG, type CatalogEntry } from '@bg/shared';
import { CATALOG, CHAT_SOUND_DEFAULT, CHAT_SOUND_MAX, CHAT_SOUND_MIN, GAME_SPEED_DEFAULT, GAME_SPEED_MAX, GAME_SPEED_MIN, type CatalogEntry } from '@bg/shared';
export const SiteSettingsSchema = z.object({
siteName: z.string().trim().min(1).max(40).default('같이 놀자 보드게임'),
@@ -17,6 +17,12 @@ export const SiteSettingsSchema = z.object({
graceSec: z.number().int().min(10).max(600).default(60),
chatEnabledDefault: z.boolean().default(true),
chatFilterDefault: z.boolean().default(true),
/** Chat flood guard (per-socket chat budget, docs/03 §8). Off: chat lines and 입력 중 signals are never limited. */
chatFloodGuard: z.boolean().default(false),
/** Animations and the computers' thinking time are divided by this (applies at once, also to running games). */
gameSpeed: z.number().min(GAME_SPEED_MIN).max(GAME_SPEED_MAX).default(GAME_SPEED_DEFAULT),
/** Chat sound in % of a game sound (0 = silent, applies at once, also to open rooms). */
chatSound: z.number().int().min(CHAT_SOUND_MIN).max(CHAT_SOUND_MAX).default(CHAT_SOUND_DEFAULT),
});
export type SiteSettings = z.infer<typeof SiteSettingsSchema>;

298
apps/server/src/ai/acts.ts Normal file
View 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;
}

View File

@@ -0,0 +1,667 @@
/** Computers with the local model (docs/06 §12.1): client limits, clean lines, and how rooms use it. */
import { afterEach, describe, expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import { botProfile, isBotId } from '@bg/shared';
import { openDb } from '../db';
import { RoomManager } from '../rooms/manager';
import type { Room } from '../rooms/room';
import { RoomStore } from '../rooms/store';
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';
/** A fake Ollama: answers with `reply(prompt)`; records the prompts. */
function fakeOllama(reply: (user: string, body: { format?: unknown }) => string | Error) {
const prompts: string[] = [];
const fetchFn = (async (_url: string, init: RequestInit) => {
const body = JSON.parse(String(init.body)) as { messages: { role: string; content: string }[]; format?: unknown };
const user = body.messages.find((m) => m.role === 'user')!.content;
prompts.push(user);
const r = reply(user, body);
if (r instanceof Error) throw r;
return new Response(JSON.stringify({ message: { content: r } }), { headers: { 'content-type': 'application/json' } });
}) as unknown as typeof fetch;
return { fetchFn, prompts };
}
describe('Llm client', () => {
test('returns the text; a few failures in a row back off; a full queue is refused at once', async () => {
let fail = false;
const { fetchFn } = fakeOllama(() => (fail ? new Error('down') : '안녕'));
let now = 0;
const llm = new Llm({ url: 'http://x', model: 'm', fetch: fetchFn, now: () => now, maxQueue: 0, maxConcurrent: 1 });
expect(await llm.chat([{ role: 'user', content: 'hi' }])).toBe('안녕');
fail = true;
for (let i = 0; i < 3; i++) expect(await llm.chat([{ role: 'user', content: 'hi' }])).toBeNull();
expect(llm.available()).toBe(false);
expect(await llm.chat([{ role: 'user', content: 'hi' }])).toBeNull(); // skipped, not even sent
expect(llm.stats.skipped).toBe(1);
now += 31_000;
fail = false;
expect(llm.available()).toBe(true);
// One running, no waiting room: the second is refused immediately.
const a = llm.chat([{ role: 'user', content: 'a' }]);
const b = await llm.chat([{ role: 'user', content: 'b' }]);
expect(b).toBeNull();
expect(await a).toBe('안녕');
});
test('a hung model times out', 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 llm = new Llm({ url: 'http://x', model: 'm', fetch: hang, timeoutMs: 30 });
expect(await llm.chat([{ role: 'user', content: 'hi' }])).toBeNull();
expect(llm.stats.failed).toBe(1);
});
});
describe('clean lines', () => {
test('one short Korean line; quotes, names and markdown stripped; foreign, AI talk and bad words refused', () => {
expect(cleanLine('"흐음, 또 막았네? 😎 잘 봤다!"')).toBe('흐음, 또 막았네? 😎 잘 봤다!');
expect(cleanLine('컴퓨터 2: 이번엔 내가 이긴다!\n두 번째 줄')).toBe('이번엔 내가 이긴다!');
expect(cleanLine('**좋아요**')).toBe('좋아요');
expect(cleanLine('철수님真爱吗')).toBeNull();
expect(cleanLine('Nice move, buddy!')).toBeNull();
expect(cleanLine('저는 AI라서 잘 몰라요')).toBeNull();
expect(cleanLine('시발 뭐야')).toBeNull();
expect(cleanLine('www.example.com 와봐')).toBeNull();
expect(cleanLine('나 마피아임 ㅋㅋ', 40, [/(나|저)\s*마피아/])).toBeNull();
// Too long: cut at a sentence end, or refused when there is none early enough.
expect(cleanLine('이번 판은 정말 재밌겠네요. 다들 준비됐나요', 20)).toBe('이번 판은 정말 재밌겠네요.');
expect(cleanLine('가'.repeat(80), 20)).toBeNull();
});
test('every computer has one of five characters, fixed by its id', () => {
const seen = new Set(Array.from({ length: 200 }, (_, i) => temperOf(`bot:${i}:x`).key));
expect(seen.size).toBe(TEMPERS.length);
expect(temperOf('bot:1:abc')).toBe(temperOf('bot:1:abc'));
});
});
// ---------------------------------------------------------------- rooms
const rooms: Room[] = [];
afterEach(() => {
for (const r of rooms.splice(0)) r.clearTimer();
});
function harness(reply: (user: string, body: { format?: unknown }) => string | Error, random = () => 0) {
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 === 'A' ? '철수' : id, avatar: null, kind: 'guest' as const } };
const { fetchFn, prompts } = fakeOllama(reply);
const ai = new Llm({ url: 'http://gpu', model: 'gemma3:4b', fetch: fetchFn });
const slept: number[] = [];
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0, ai, aiRandom: random, aiSleep: async (ms) => {
// Typing takes time on the room clock too.
slept.push(ms);
clock.advance(ms);
} });
const conn = (userId: string) => {
const msgs: import('@bg/shared').ServerMessage[] = [];
return { userId, msgs, send: (m: (typeof msgs)[number]) => msgs.push(m), close: () => {} };
};
return { manager, clock, conn, prompts, slept, store };
}
const settle = () => new Promise((r) => setTimeout(r, 5));
describe('rooms with the model', () => {
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' }, 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);
// 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();
});
test('a person asks a computer by name: it answers in the room chat', async () => {
const h = harness(() => '저요? 저 오목 잘 둬요 ㅎㅎ', () => 0.99);
const room = h.manager.createPractice('A', 'omok') as Room;
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();
expect(a.msgs.some((m) => m.t === 'chat' && (m as { text: string }).text === '저요? 저 오목 잘 둬요 ㅎㅎ')).toBe(true);
expect(h.prompts.at(-1)).toContain('컴퓨터 1 오목 잘해?');
});
test('without a model, or with a model that is down, computers play silently as before', async () => {
const h = harness(() => new Error('down'));
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' } });
expect(room.start('A')).toBeNull();
for (let i = 0; i < 3; i++) {
room.act('A', i + 1, { type: 'place', x: [0, 14, 0][i]!, y: [0, 14, 14][i]! }); // corners: the computer never needs them
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')).toBe(false);
});
test('바퀴벌레 포커: the model decides truth or bluff; telling the truth sets the real kind', async () => {
let checked = false;
// The starter is random: try new rooms until the computer offers first.
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(`A${attempt}`, 'cockroach-poker') as Room;
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;
await settle(); // the start greeting goes out first
h.clock.advance(20_000);
for (let i = 0; i < 30 && !st().round.claim; i++) {
room.bots.fire();
await settle();
}
const kind = st().round.card!.replace(/-\d+$/, '');
expect(st().round.claim).toBe(kind);
expect(a.msgs.some((m) => m.t === 'chat' && (m as { text: string }).text === '이건 진짜야, 믿어봐~')).toBe(true);
checked = true;
}
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 ? '안녕하세요~ 오늘 마피아 꼭 잡아봐요!' : '저 경찰이에요 믿어주세요'));
const room = h.manager.createPractice('A', 'mafia') as Room;
rooms.push(room);
room.join(h.conn('A'), 'player');
expect(room.start('A')).toBeNull();
for (let i = 0; i < 4 * 40; 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();
await settle();
}
const chat = (room.game!.state as { chat: { from: string; channel: string; text: string }[] }).chat.filter((m) => isBotId(m.from) && m.channel === 'day');
expect(chat.length).toBeGreaterThan(0);
expect(chat.some((m) => m.text === '안녕하세요~ 오늘 마피아 꼭 잡아봐요!')).toBe(true);
expect(chat.some((m) => m.text === '저 경찰이에요 믿어주세요')).toBe(false);
});
});
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(700);
expect(long).toBeGreaterThan(short);
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);
});
});

473
apps/server/src/ai/brain.ts Normal file
View File

@@ -0,0 +1,473 @@
/**
* A room's computers, played like people with the local model (docs/06 §12.1).
*
* - 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 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';
export type BotActivity = 'thinking' | 'typing';
export interface BrainRoom {
gameId(): string;
gameName(): string;
nameOf(id: string): string;
/** People and computers seated in the running game. */
humans(): string[];
bots(): string[];
playing(): boolean;
/** Posts in the room chat as `bot` (games without their own chat channels). */
roomChat(bot: string, text: string): void;
setActivity(bot: string, a: BotActivity | null): void;
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;
}
/** 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: 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,
readonly llm: Llm | null,
private random: () => number = secureRandom,
private sleep: (ms: number) => Promise<void> = sleepReal,
) {}
/** The model is set up and answering, and there is someone to play for. */
enabled(): boolean {
return !!this.llm && this.llm.available() && this.room.playing() && this.room.humans().length > 0;
}
/** 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 = (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, alreadyMs = 0): Promise<void> {
this.busy.add(bot);
this.showTyping(bot, true);
try {
await this.sleep(Math.max(0, this.typingMs(bot, text) - alreadyMs));
} finally {
this.showTyping(bot, false);
this.busy.delete(bot);
}
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 {
return {
bot,
name: this.room.nameOf(bot),
smart: this.room.smart(bot),
game: this.room.gameName(),
situation,
task,
recent: this.room.recentChat(),
...extra,
};
}
/** 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 >= TALK_ROOM_GAP && now - (this.lastBotLine.get(bot) ?? -Infinity) >= TALK_BOT_GAP && !this.busy.has(bot);
}
private spoke(bot: string): void {
const now = this.room.now();
this.lastRoomLine = now;
this.lastBotLine.set(bot, now);
}
/** 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);
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');
}
/** 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;
const meaning = meaningOf(this.room.gameId(), action);
this.happened.push({ actor, meaning });
if (this.happened.length > 12) this.happened.shift();
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);
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!));
});
}
/**
* Before a computer's own move: maybe a word with it (typed first, then the move), and in 바퀴벌레 포커 the
* truth-or-bluff choice. Returns the action to play (possibly with a different claim).
*/
async beforeMove(bot: string, action: unknown, view: unknown): Promise<unknown> {
if (!this.enabled()) return action;
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;
// 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 (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() && !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;
}
/** 바퀴벌레 포커: the model decides to tell the truth or bluff (and what to say); the strategy picked card and person. */
private async cockroachBluff(bot: string, a: { type?: string; claim?: string; cardId?: string; to?: string }, view: unknown): Promise<{ action: unknown; say: string | null } | null> {
const v = view as { myHand?: { kind: string; ids: string[] }[]; card?: { known: boolean; kind?: string } | null; fronts?: Record<string, { counts: Record<string, number> }> };
const kind = a.type === 'offer' ? v.myHand?.find((g) => g.ids.includes(a.cardId!))?.kind : v.card?.known ? v.card.kind : undefined;
if (!kind || !a.to) return null;
const KO: Record<string, string> = { cockroach: '바퀴벌레', bat: '박쥐', fly: '파리', toad: '두꺼비', rat: '쥐', scorpion: '전갈', spider: '거미', stinkbug: '노린재' };
const target = this.room.nameOf(a.to);
const front = v.fronts?.[a.to]?.counts ?? {};
const pile = Object.entries(front).filter(([, n]) => n > 0).map(([k, n]) => `${KO[k] ?? k} ${n}장`).join(', ') || '없음';
const r = await decide<{ bluff: boolean; say: string }>(
this.llm,
bot,
this.room.nameOf(bot),
this.room.smart(bot),
`바퀴벌레 포커. 나는 ${target}에게 카드를 건넨다. 실제 카드는 ${KO[kind] ?? kind}다. ${target}의 앞마당: ${pile}.\n` +
`진짜 이름을 말할지(bluff=false) 다른 벌레라고 거짓말할지(bluff=true) 정하고, 건네며 할 한마디(say, 30자 이내, 실제 카드를 밝히지 말 것)를 정해.`,
{ type: 'object', properties: { bluff: { type: 'boolean' }, say: { type: 'string' } }, required: ['bluff', 'say'] },
);
if (!r) return null;
let claim = a.claim!;
if (r.bluff && claim === kind) claim = Object.keys(KO).filter((k) => k !== kind)[Math.floor(this.random() * 7)]!;
if (!r.bluff) claim = kind;
// The line must not give the real card away.
const say = cleanLine(String(r.say ?? ''), 36, [new RegExp(KO[kind] ?? kind)]);
// Selling the claim is part of the move, so it is said even right after another line.
return { action: { ...a, claim }, say };
}
/**
* 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 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 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.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 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);
});
}
/**
* 마피아: a computer's planned line (`hint` = what it means, `text` = built-in wording) in its own words. The model is
* told only what the line means and the public chat — never the computer's role — and a line that claims a role
* or "I'm mafia" is thrown away. Returns the built-in text when there is no usable answer.
*/
async mafiaLine(bot: string, hint: string, text: string, recent: { from: string; text: string }[]): Promise<string> {
if (!this.llm?.available()) return text;
const line = await writeLine(this.llm, {
bot,
name: this.room.nameOf(bot),
smart: this.room.smart(bot),
game: '마피아(낮 토론, 모두가 보는 채팅)',
situation: '누가 마피아인지 추리하며 이야기하는 중이다. 너는 자신이 시민 팀이라고 말한다.',
task: hint,
recent,
example: text,
maxLen: 45,
// Never a role claim of its own ("저 경찰이에요", "나 마피아임"): the plan decides those, word for word.
forbid: [/(저|제가|나|내가|난|전)\s*(는|가|도)?\s*(진짜\s*)?(마피아|경찰|의사|군인|정치인|영매|연인)/],
});
return line ?? text;
}
}

143
apps/server/src/ai/lines.ts Normal file
View File

@@ -0,0 +1,143 @@
/**
* What a computer says, written by the local model (docs/06 §12.1): a character (성격 + 말투) per computer, a prompt
* per moment, and a strict clean-up so only one short, kind, Korean chat line ever reaches people.
*/
import { hash01 } from '@bg/games/bots';
import { chatProblem } from '@bg/games/mafia';
import type { Llm, LlmMessage } from './llm';
export interface Temper {
key: 'taunt' | 'bluff' | 'calm' | 'chatty' | 'timid';
ko: string;
desc: string;
/** How often it speaks up on its own move (before rate limits). */
talk: number;
}
export const TEMPERS: readonly Temper[] = [
{ key: 'taunt', ko: '도발형', desc: '장난스럽게 상대를 도발하고 약을 올린다. 그래도 욕이나 비하는 절대 하지 않는다.', talk: 0.32 },
{ key: 'bluff', ko: '허세형', desc: '자신감이 넘치고 허세를 부린다. 질 것 같아도 이길 거라고 큰소리친다.', talk: 0.28 },
{ key: 'calm', ko: '차분형', desc: '차분하고 담담하다. 짧게 말하고, 가끔 날카로운 한마디로 심리전을 건다.', talk: 0.14 },
{ key: 'chatty', ko: '수다형', desc: '말이 많고 리액션이 크다. 감탄사를 자주 쓴다.', talk: 0.38 },
{ key: 'timid', ko: '소심형', desc: '소심하고 엄살이 많다. 걱정하는 척하면서 은근히 상대를 떠본다.', talk: 0.18 },
];
/** Each computer's character: 성격 from its id, 말투 from 똑똑한 편(존댓말)/허술한 편(반말). */
export function temperOf(bot: string): Temper {
return TEMPERS[Math.floor(hash01(bot, 'temper') * TEMPERS.length)]!;
}
/** `smart` = 똑똑한 편 (the room's `botPersona`). */
export function speechOf(smart: boolean): string {
return smart ? '존댓말(해요체), 또박또박' : '반말, 짧고 가볍게, ㅋㅋ를 가끔 붙임';
}
export function systemPrompt(bot: string, name: string, maxLen: number, smart: boolean): string {
const t = temperOf(bot);
return [
`너는 온라인 보드게임 사이트 "같이 놀자"에서 사람들과 함께 게임하는 컴퓨터 플레이어 "${name}"이다.`,
`성격: ${t.ko} — ${t.desc}`,
`말투: ${speechOf(smart)}.`,
`규칙: 한국어 채팅 한 줄만 쓴다. ${maxLen}자 이내. 대사만 쓰고 따옴표·설명·괄호·영어·한자는 쓰지 않는다.`,
'욕설·막말·깔보는 호칭, 비하, 외모·성별·나이 언급, 개인정보, 링크는 절대 쓰지 않는다. 상대가 거친 말을 해도 장난스럽게 받아넘긴다.',
'"상황"에 적힌 사실에만 근거해서 말한다. 적히지 않은 점수·패·행동은 지어내지 않고, 게임과 상관없는 혼잣말이나 "다들 준비됐냐" 같은 뻔한 말은 하지 않는다.',
'최근 채팅에서 "(나)"가 붙은 줄은 내가 한 말이다. 내가 했던 말의 시작이나 표현을 되풀이하지 않는다.',
'누가 한 수의 뜻이 적혀 있으면 그 뜻에 맞게 말한다(센 베팅을 한 사람에게 겁먹었다고 하지 않고, 포기한 사람에게 세게 나왔다고 하지 않는다).',
'자신이 AI나 프로그램이라고 말하지 않는다. 숨겨진 정보(내 패, 내 카드, 내 직업)는 절대 밝히지 않는다.',
].join('\n');
}
export interface LineRequest {
bot: string;
name: string;
/** 똑똑한 편 (존댓말) / 허술한 편 (반말). */
smart: boolean;
game: string;
/** What is going on, in plain Korean. */
situation: string;
/** What to say now. */
task: string;
/** Recent chat, oldest first. */
recent?: { from: string; text: string }[];
/** Example line (the built-in one), so the model keeps the meaning. */
example?: string;
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 {
let line = raw
.split('\n')
.map((l) => l.trim())
.find((l) => l.length > 0);
if (!line) return null;
line = line
.replace(/^[^::]{1,12}[::]\s*/, (m) => (/[ㄱ-ㅎ가-힣]/.test(m) && m.length <= 12 ? '' : m)) // "컴퓨터 2: …"
.replace(/^["'“”‘’`「」『』]+|["'“”‘’`「」『』]+$/g, '')
.replace(/[*_#>]/g, '')
.replace(/\s+/g, ' ')
.trim();
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('');
const end = Math.max(cut.lastIndexOf('.'), cut.lastIndexOf('!'), cut.lastIndexOf('?'), cut.lastIndexOf('~'));
if ([...line].length > maxLen * 1.6 || end < maxLen * 0.4) return null;
line = cut.slice(0, end + 1);
}
if (!/[가-힣ㅋㅎㅠ]/.test(line)) return null;
if (chatProblem(line, true)) return null;
if (forbid.some((re) => re.test(line!))) return null;
return line;
}
/** Asks the model for one line; null when the model is unavailable or wrote nothing usable. */
export async function writeLine(llm: Llm | null, req: LineRequest): Promise<string | null> {
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.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') },
];
// 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);
}
/** Structured choice (JSON schema) — e.g. 바퀴벌레 포커: tell the truth or bluff, and what to say. */
export async function decide<T>(llm: Llm | null, bot: string, name: string, smart: boolean, prompt: string, schema: object): Promise<T | null> {
if (!llm || !llm.available()) return null;
const raw = await llm.chat(
[
{ role: 'system', content: systemPrompt(bot, name, 40, smart) + '\n대답은 요청한 JSON 형식으로만 한다.' },
{ role: 'user', content: prompt },
],
{ maxTokens: 120, temperature: 0.9, format: schema },
);
if (raw === null) return null;
try {
return JSON.parse(raw) as T;
} catch {
return null;
}
}

148
apps/server/src/ai/llm.ts Normal file
View File

@@ -0,0 +1,148 @@
/**
* Local language model on the GPU (Ollama, docs/11 §8). Used by computer players to talk and think out loud
* (docs/06 §12.1). Everything here is best effort: when the model is slow, busy or down the caller gets `null`
* and the computers fall back to their built-in lines — a game never waits on the model.
*/
export interface LlmMessage {
role: 'system' | 'user' | 'assistant';
content: string;
}
export interface LlmConfig {
/** Ollama base URL, e.g. http://192.168.10.9:11434. */
url: string;
model: string;
/**
* 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;
timeoutMs?: number;
/** How long Ollama keeps the model in GPU memory after the last request. */
keepAlive?: string;
fetch?: typeof fetch;
log?: (level: 'info' | 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void;
now?: () => number;
}
export interface LlmStats {
model: string;
requests: number;
ok: number;
failed: number;
/** Refused because the queue was full or the model was backing off. */
skipped: number;
avgMs: number;
lastError: string | null;
backingOffUntil: number | null;
}
export class Llm {
private running = 0;
private waiting: { go: () => void; high: boolean }[] = [];
private totalMs = 0;
private backoffUntil = 0;
private failures = 0;
readonly stats: LlmStats;
constructor(private cfg: LlmConfig) {
this.stats = { model: cfg.model, requests: 0, ok: 0, failed: 0, skipped: 0, avgMs: 0, lastError: null, backingOffUntil: null };
}
private now(): number {
return this.cfg.now ? this.cfg.now() : Date.now();
}
/** False while backing off after errors (then callers don't even try). */
available(): boolean {
return this.now() >= this.backoffUntil;
}
/**
* 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). `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; priority?: 'high' | 'normal' | 'low'; stop?: string[] } = {},
): Promise<string | null> {
this.stats.requests++;
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 (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);
try {
const res = await (this.cfg.fetch ?? fetch)(`${this.cfg.url.replace(/\/$/, '')}/api/chat`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
signal: ctl.signal,
body: JSON.stringify({
model: this.cfg.model,
messages,
stream: false,
keep_alive: this.cfg.keepAlive ?? '2h',
...(opts.format ? { format: opts.format } : {}),
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}`);
const body = (await res.json()) as { message?: { content?: string } };
const text = body.message?.content ?? '';
const ms = this.now() - t0;
this.stats.ok++;
this.totalMs += ms;
this.stats.avgMs = Math.round(this.totalMs / this.stats.ok);
this.failures = 0;
return text;
} catch (err) {
this.stats.failed++;
this.stats.lastError = String(err).slice(0, 200);
this.failures++;
// A few failures in a row: stop asking for a while (30 s, up to 5 min) instead of slowing every move.
if (this.failures >= 3) {
this.backoffUntil = this.now() + Math.min(300_000, 30_000 * 2 ** (this.failures - 3));
this.stats.backingOffUntil = this.backoffUntil;
this.cfg.log?.('warn', 'ai backing off', { failures: this.failures, err: this.stats.lastError });
}
return null;
} finally {
clearTimeout(timer);
const next = this.waiting.shift();
if (next) next.go();
else this.running--;
}
}
private lastWarm = -Infinity;
/**
* Loads the model into GPU memory ahead of the first real request (a cold load takes ~20 s; Ollama unloads it after
* `keepAlive` without use). Cheap when it is already loaded; at most once a minute.
*/
async warm(): Promise<boolean> {
if (this.now() - this.lastWarm < 60_000) return true;
this.lastWarm = this.now();
const r = await this.chat([{ role: 'user', content: '안녕' }], { maxTokens: 1, timeoutMs: 60_000 });
return r !== null;
}
}

View File

@@ -12,6 +12,8 @@ export interface Config {
superadminDiscordIds: string[];
/** Load-test only: lift per-IP HTTP limits. Ignored for https origins. */
loadTestNoHttpLimits: boolean;
/** Local language model for the computers (docs/06 §12.1, docs/11 §8); null = computers play without it. */
ai: { url: string; model: string } | null;
}
export function loadConfig(env: Record<string, string | undefined> = process.env): Config {
@@ -35,5 +37,7 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
loadTestNoHttpLimits: env.LOADTEST_NO_HTTP_LIMITS === '1' && !publicOrigin.startsWith('https://'),
/** Superadmin Discord IDs, comma-separated (docs/14-admin.md §2). Only in deploy/.env, never in the repo. */
superadminDiscordIds: (env.SUPERADMIN_DISCORD_IDS ?? '').split(',').map((s) => s.trim()).filter(Boolean),
/** AI_URL = Ollama on the GPU host (e.g. http://host.docker.internal:11434); AI_MODEL defaults to gemma3:4b. */
ai: env.AI_URL ? { url: env.AI_URL, model: env.AI_MODEL || 'gemma3:4b' } : null,
};
}

View File

@@ -0,0 +1,5 @@
-- 라이어 게임 제시어 관리 (docs/games/liar.md §3.1, docs/14-admin.md §4.1).
-- One row per changed topic: a built-in topic replaced ({"topic":…}) or deleted ({"deleted":true}), or an admin's own topic (id c_…).
CREATE TABLE liar_topics (id TEXT PRIMARY KEY, json TEXT NOT NULL, created_at INTEGER NOT NULL, updated_by TEXT, updated_at INTEGER NOT NULL);
-- Every set of changes games were started with (options.bank = ref), so replays set up from the same bank.
CREATE TABLE liar_bank_versions (ref TEXT PRIMARY KEY, json TEXT NOT NULL, created_at INTEGER NOT NULL);

View File

@@ -93,12 +93,51 @@ describe('idle guests', () => {
});
describe('leaving the room page', () => {
test('detach keeps the seat but the room no longer counts the connection', async () => {
test('alone with no game running (뒤로가기 from the lobby): leaving the page leaves the room and it closes at once', async () => {
const s = start();
const g = await guest(s.base, '혼자');
const c = await connect(s, g);
const r = await api(s.base, '/api/rooms', { method: 'POST', cookie: c.cookie, body: JSON.stringify({ gameId: 'omok' }) });
c.send({ t: 'join', code: r.body.code, as: 'player' });
await c.waitFor((m) => m.t === 'room');
expect(s.rooms.get(r.body.code)).toBeDefined();
c.send({ t: 'detach' });
for (let i = 0; i < 50 && s.rooms.get(r.body.code); i++) await sleep(10);
expect(s.rooms.get(r.body.code)).toBeUndefined();
expect(s.rooms.activeRoomFor(g.id)).toBeNull();
// The same socket is fine afterwards.
c.send({ t: 'ping', ts: 1 });
await c.waitFor((m) => m.t === 'pong');
});
test('someone else is in the lobby: leaving the page keeps my seat (I can come back)', async () => {
const s = start();
const a = await guest(s.base, '방장');
const b = await guest(s.base, '친구');
const ca = await connect(s, a);
const cb = await connect(s, b);
const r = await api(s.base, '/api/rooms', { method: 'POST', cookie: ca.cookie, body: JSON.stringify({ gameId: 'omok' }) });
ca.send({ t: 'join', code: r.body.code, as: 'player' });
await ca.waitFor((m) => m.t === 'room');
cb.send({ t: 'join', code: r.body.code, as: 'player' });
await cb.waitFor((m) => m.t === 'room');
const room = s.rooms.get(r.body.code)!;
ca.send({ t: 'detach' });
for (let i = 0; i < 50 && room.conns.size > 1; i++) await sleep(10);
expect(room.conns.size).toBe(1);
expect(room.seatOf(a.id)).toBeGreaterThanOrEqual(0);
expect(s.rooms.get(r.body.code)).toBe(room);
});
test('detach during a game keeps the seat but the room no longer counts the connection', async () => {
const s = start();
const g = await guest(s.base, '홈으로');
const c = await connect(s, g);
const code = await practiceRoom(s, c);
const room = s.rooms.get(code)!;
c.send({ t: 'start' });
for (let i = 0; i < 50 && room.status !== 'playing'; i++) await sleep(10);
expect(room.status).toBe('playing');
expect(room.conns.size).toBe(1);
c.send({ t: 'detach' });
for (let i = 0; i < 50 && room.conns.size; i++) await sleep(10);

View File

@@ -5,6 +5,7 @@ import type { AnyGameDefinition } from '@bg/engine';
import { botProfile, nicknameError, normalizeNickname } from '@bg/shared';
import type { Audit, Role, Roles } from '../admin/roles';
import { GameSettingsSchema, SiteSettingsSchema, type SettingsStore } from '../admin/settings';
import { LiarTopicInputSchema, type LiarBankStore } from '../admin/liar-bank';
import type { Sessions } from '../auth/sessions';
import { toPublicUser, type Users } from '../auth/users';
import type { RoomManager } from '../rooms/manager';
@@ -19,6 +20,7 @@ export interface AdminDeps {
audit: Audit;
settings: SettingsStore;
games: Record<string, AnyGameDefinition>;
liarBank: LiarBankStore;
disconnectUser: (userId: string) => void;
/** When an idle guest will be deleted; null for members and for guests still online or seated. */
guestDeleteAt: (u: { id: string; kind: 'guest' | 'member'; last_seen_at: number }) => number | null;
@@ -85,6 +87,57 @@ export function createAdminApp(d: AdminDeps) {
return c.json({ effective: d.settings.game(id), raw: {} });
});
// ------------------------------------------------------------ 라이어 게임 topics and words (docs/14-admin.md §4.1)
app.get('/liar/topics', (c) => c.json({ topics: d.liarBank.list() }));
/** Parses and checks a topic as typed; the error response, or the topic. */
const liarInput = async (c: Context<Env>) => {
const parsed = LiarTopicInputSchema.safeParse(await body(c));
if (!parsed.success) return { error: c.json({ error: `입력 값이 올바르지 않아요: ${parsed.error.issues.map((i) => i.path.join('.') + ' ' + i.message).join(', ')}` }, 400) };
const problems = d.liarBank.problems(parsed.data);
if (problems.length) return { error: c.json({ error: problems.slice(0, 30).join('\n'), problems }, 400) };
return { topic: parsed.data };
};
app.post('/liar/topics', async (c) => {
const r = await liarInput(c);
if (r.error) return r.error;
const id = d.liarBank.create(r.topic, actor(c));
if (!id) return c.json({ error: '주제는 100개까지 더할 수 있어요.' }, 400);
d.audit.log(actor(c), 'liar.topic.create', id, null, r.topic);
return c.json({ topic: d.liarBank.get(id) });
});
app.put('/liar/topics/:id', async (c) => {
const id = c.req.param('id');
const before = d.liarBank.get(id);
if (!before) return c.json({ error: '없는 주제예요.' }, 404);
const r = await liarInput(c);
if (r.error) return r.error;
d.liarBank.save(id, r.topic, actor(c));
d.audit.log(actor(c), 'liar.topic.update', id, before, r.topic);
return c.json({ topic: d.liarBank.get(id) });
});
app.delete('/liar/topics/:id', (c) => {
const id = c.req.param('id');
const before = d.liarBank.get(id);
if (!before || before.deleted) return c.json({ error: '없는 주제예요.' }, 404);
if (d.liarBank.list().filter((t) => !t.deleted).length <= 1) return c.json({ error: '주제가 하나는 있어야 해요.' }, 400);
d.liarBank.delete(id, actor(c));
d.audit.log(actor(c), 'liar.topic.delete', id, before, null);
return c.json({ ok: true });
});
app.post('/liar/topics/:id/reset', (c) => {
const id = c.req.param('id');
const before = d.liarBank.get(id);
if (!before?.builtin) return c.json({ error: '처음부터 있던 주제만 되돌릴 수 있어요.' }, 400);
d.liarBank.reset(id);
d.audit.log(actor(c), 'liar.topic.reset', id, before, null);
return c.json({ topic: d.liarBank.get(id) });
});
// ------------------------------------------------------------ site
app.get('/site', (c) => c.json({ site: d.settings.getSite() }));
app.put('/site', async (c) => {
@@ -93,6 +146,8 @@ export function createAdminApp(d: AdminDeps) {
const before = d.settings.getSite();
d.settings.setSite(parsed.data, actor(c));
d.audit.log(actor(c), 'site.update', null, before, parsed.data);
// The game speed and chat sound apply at once: open rooms get them with a fresh room view.
if (before.gameSpeed !== parsed.data.gameSpeed || before.chatSound !== parsed.data.chatSound) for (const r of d.rooms.all()) r.broadcastRoom();
return c.json({ site: parsed.data });
});

View File

@@ -2,6 +2,7 @@
import { Hono, type Context } from 'hono';
import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
import { z } from 'zod';
import { bankTopics, liarBankRef } from '@bg/games/liar';
import { nicknameError, normalizeNickname, normalizeRoomCode, formatRoomCode } from '@bg/shared';
import type { Config } from '../config';
import { authorizeUrl, avatarUrl, exchangeCode, safeNext, type DiscordUser } from '../auth/discord';
@@ -16,6 +17,8 @@ import type { SettingsStore } from '../admin/settings';
export interface HttpDeps {
config: Config;
/** Web build being served (`/api/version`, docs/07 §11.1); null without a web build. */
build?: string | null;
users: Users;
sessions: Sessions;
rooms: RoomManager;
@@ -76,6 +79,12 @@ export function createHttpApp(d: HttpDeps) {
setCookie(c, SESSION_COOKIE, token, cookieOpts(SESSION_TTL[kind]));
};
// Open pages ask now and then whether the site was updated (docs/07 §11.1).
app.get('/api/version', (c) => {
c.header('Cache-Control', 'no-store');
return c.json({ build: d.build ?? null });
});
app.get('/healthz', (c) => {
const h = d.health();
return c.json(h, h.ok ? 200 : 503);
@@ -89,9 +98,14 @@ export function createHttpApp(d: HttpDeps) {
siteName: site.siteName,
announcement: site.announcement,
maintenance: site.maintenance,
gameSpeed: site.gameSpeed,
chatSound: site.chatSound,
});
});
// 라이어 게임 topics new games can use (admins may add or delete some): the lobby's 주제 choices.
app.get('/api/liar/topics', (c) => c.json({ topics: bankTopics(liarBankRef()).map((t) => ({ id: t.id, ko: t.ko, words: t.words.length })) }));
app.post('/api/auth/guest', async (c) => {
if (!guestLimiter.allow(d.ipOf(c.req.raw))) return c.json({ error: '잠시 후 다시 시도해 주세요.' }, 429);
const body = z.object({ nickname: z.string().max(100) }).safeParse(await c.req.json().catch(() => null));

View 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('모두 끝냈어요');
});
});

View File

@@ -0,0 +1,238 @@
/** Computer levels 1~60, the host's 쉬움/보통/어려움, drift between games and luck shuffles (docs/09 §9.1, docs/04 §5.1). */
import { afterEach, describe, expect, test } from 'bun:test';
import { seedToHex, type ChaChaSeed } from '@bg/engine';
import { GAMES } from '@bg/games';
import { BOT_BANDS, ClientMessage, bandOf, botProfile, isBotId, luckLabel, type ServerMessage } from '@bg/shared';
import type { LuckJob } from '@bg/games/bots/luck';
import { openDb } from '../db';
import { sha256Hex } from '../auth/sessions';
import { DRIFT_RANGE, DRIFT_STEP, drift, newBotProfile, profileFromId, repick, rollLevel } from './bot-profile';
import { RoomManager } from './manager';
import { Room, type Conn, type RoomSnapshot } from './room';
import { RoomStore } from './store';
const rooms: Room[] = [];
afterEach(() => {
for (const r of rooms.splice(0)) r.clearTimer();
});
function harness(luckSeed?: (job: LuckJob) => Promise<{ seed: ChaChaSeed; tried: number }>) {
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: () => 60_000, luckSeed });
const conn = (userId: string) => {
const msgs: ServerMessage[] = [];
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
return c;
};
const practice = (gameId: string) => {
const r = manager.createPractice('A', gameId) as Room;
rooms.push(r);
r.join(conn('A'), 'player');
return r;
};
return { db, store, clock, manager, conn, practice, users };
}
const botsOf = (room: Room) => room.seatedIds().filter(isBotId);
const seq = (...xs: number[]) => {
let i = 0;
return () => xs[i++ % xs.length]!;
};
describe('levels', () => {
test('rolls: 랜덤 1~60, 쉬움 1~20, 보통 21~40, 어려움 41~60, all values reachable', () => {
for (const pick of ['random', 'easy', 'normal', 'hard'] as const) {
const [lo, hi] = pick === 'random' ? [1, 60] : BOT_BANDS[pick];
expect(rollLevel(pick, () => 0)).toBe(lo);
expect(rollLevel(pick, () => 0.999999)).toBe(hi);
for (let i = 0; i < 500; i++) {
const l = rollLevel(pick);
expect(l >= lo && l <= hi).toBe(true);
}
}
expect(bandOf(20)).toBe('easy');
expect(bandOf(21)).toBe('normal');
expect(bandOf(41)).toBe('hard');
});
test('a new computer: any level, its own luck in [-1, 1]; picking a band keeps the luck', () => {
const p = newBotProfile(seq(0.5, 0.9));
expect(p).toEqual({ pick: 'random', base: 31, level: 31, luck: expect.closeTo(0.8, 9), played: 0 });
const q = repick(p, 'easy', () => 0.3);
expect(q).toEqual({ pick: 'easy', base: 7, level: 7, luck: p.luck, played: 0 });
expect(luckLabel(-1)).toBe('아주 나쁨');
expect(luckLabel(0)).toBe('보통');
expect(luckLabel(0.7)).toBe('아주 좋음');
});
test('drift: none before the first game, then at most 2 a game, within ±5 of the start and never out of its band', () => {
for (const base of [1, 20, 21, 33, 41, 60]) {
let p = { ...newBotProfile(), base, level: base };
p = drift(p);
expect(p.level).toBe(base);
const [lo, hi] = BOT_BANDS[bandOf(base)];
for (let g = 0; g < 300; g++) {
const prev = p.level;
p = drift(p);
expect(Math.abs(p.level - prev)).toBeLessThanOrEqual(DRIFT_STEP);
expect(Math.abs(p.level - base)).toBeLessThanOrEqual(DRIFT_RANGE);
expect(p.level >= lo && p.level <= hi).toBe(true);
}
}
// A 60 can become 58 next game, never 41.
expect(drift({ ...newBotProfile(), base: 60, level: 60, played: 1 }, () => 0).level).toBe(58);
});
test('computers saved without a level get one from their id (the same every time)', () => {
const id = 'bot:1:01J0000000ZZZZZZ0000000000';
expect(profileFromId(id)).toEqual(profileFromId(id));
expect(profileFromId(id).level).toBe(60);
});
});
describe('room', () => {
test('protocol accepts botLevel with the four choices only', () => {
expect(ClientMessage.safeParse({ t: 'botLevel', userId: 'bot:1:x', pick: 'hard' }).success).toBe(true);
expect(ClientMessage.safeParse({ t: 'botLevel', userId: 'bot:1:x', pick: 'insane' }).success).toBe(false);
});
test('the host picks a band; everyone sees the pick, nobody sees the level until the game is over', () => {
const { practice, conn } = harness();
const room = practice('omok');
const bot = botsOf(room)[0]!;
expect(room.profile(bot).pick).toBe('random');
expect(room.roomView().botPicks).toEqual({ [bot]: 'random' });
room.join(conn('S'), 'spectator');
expect(room.setBotLevel('S', bot, 'hard')).toBe('방장만 난이도를 바꿀 수 있어요.');
expect(room.setBotLevel('A', 'bot:9:nope', 'hard')).toBe('없는 컴퓨터예요.');
expect(room.setBotLevel('A', bot, 'hard')).toBeNull();
expect(room.roomView().botPicks).toEqual({ [bot]: 'hard' });
const level = room.profile(bot).level;
expect(level >= 41 && level <= 60).toBe(true);
expect(JSON.stringify(room.roomView())).not.toContain('"level"');
expect(room.start('A')).toBeNull();
expect(room.setBotLevel('A', bot, 'easy')).toBe('게임 중에는 바꿀 수 없어요.');
expect(room.roomView().lastBots).toBeUndefined();
room.act('A', 1, { type: 'resign' });
expect(room.status).toBe('finished');
expect(room.roomView().lastBots).toEqual({ [bot]: { level, luck: room.profile(bot).luck } });
expect(room.roomView().lastShuffles).toBe(1);
});
test('every next game the level moves a little around where it started', () => {
const { practice } = harness();
const room = practice('omok');
const bot = botsOf(room)[0]!;
room.setBotLevel('A', bot, 'hard');
const base = room.profile(bot).base;
const seen: number[] = [];
for (let g = 0; g < 25; g++) {
expect(g === 0 ? room.start('A') : room.rematch('A')).toBeNull();
seen.push(room.game!.bots![bot]!.level);
room.act('A', g + 1, { type: 'resign' });
}
expect(seen[0]).toBe(base);
for (let i = 1; i < seen.length; i++) expect(Math.abs(seen[i]! - seen[i - 1]!)).toBeLessThanOrEqual(DRIFT_STEP);
for (const l of seen) expect(l >= Math.max(41, base - DRIFT_RANGE) && l <= Math.min(60, base + DRIFT_RANGE)).toBe(true);
expect(new Set(seen).size).toBeGreaterThan(1);
});
test('levels and luck survive a restart; rooms saved before get them from the id', () => {
const { practice, store, clock, users } = harness();
const room = practice('omok');
const bot = botsOf(room)[0]!;
room.setBotLevel('A', bot, 'easy');
const before = room.profile(bot);
const { seq: s, stateJson } = store.openRooms()[0]!;
const deps = { store, games: GAMES, users, now: clock.now, botDelay: () => 60_000 };
const restored = Room.restore(room.id, room.code, s, JSON.parse(stateJson) as RoomSnapshot, deps);
rooms.push(restored);
expect(restored.profile(bot)).toEqual(before);
const old = JSON.parse(stateJson) as RoomSnapshot;
delete old.bots;
const legacy = Room.restore(room.id, room.code, s, old, deps);
rooms.push(legacy);
expect(legacy.profile(bot)).toEqual(profileFromId(bot));
});
});
describe('luck shuffles', () => {
const seedA = [1, 2, 3, 4, 5, 6, 7, 8] as ChaChaSeed;
test('a card game with computers waits for the shuffles, then starts with the chosen seed', async () => {
const jobs: LuckJob[] = [];
let release!: () => void;
const gate = new Promise<void>((r) => (release = r));
const { practice } = harness(async (job) => {
jobs.push(job);
await gate;
return { seed: seedA, tried: 4 };
});
const room = practice('one-card');
const bot = botsOf(room)[0]!;
room.botProfiles[bot]!.luck = 0.9;
expect(room.start('A')).toBeNull();
expect(room.status).toBe('lobby');
expect(room.roomView().starting).toBe(true);
expect(room.start('A')).toBe('게임을 준비하고 있어요.');
expect(room.setBotLevel('A', bot, 'easy')).toBe('게임을 준비하고 있어요.');
expect(jobs).toHaveLength(1);
expect(jobs[0]).toMatchObject({ gameId: 'one-card', players: room.seatedIds(), luck: { [bot]: room.profile(bot).luck }, gameNo: 1 });
release();
await gate;
await Bun.sleep(0);
expect(room.status).toBe('playing');
expect(room.roomView().starting).toBeUndefined();
expect(room.game!.seedHex).toBe(seedToHex(seedA));
expect(room.game!.seedHash).toBe(sha256Hex(seedToHex(seedA)));
expect(room.game!.shuffles).toBe(4);
});
test('if the seats change while shuffling, nothing starts', async () => {
let release!: () => void;
const gate = new Promise<void>((r) => (release = r));
const { practice } = harness(async () => {
await gate;
return { seed: seedA, tried: 2 };
});
const room = practice('one-card');
room.botProfiles[botsOf(room)[0]!]!.luck = -0.9;
expect(room.start('A')).toBeNull();
room.leave('A');
release();
await gate;
await Bun.sleep(0);
expect(room.status).toBe('lobby');
expect(room.game).toBeNull();
expect(room.starting).toBe(false);
});
test('a failed shuffle job still starts the game with a fresh seed; board games and luck near 0 never ask', async () => {
const asked: string[] = [];
const { practice } = harness(async (job) => {
asked.push(job.gameId);
throw new Error('worker down');
});
const omok = practice('omok');
expect(omok.start('A')).toBeNull();
expect(omok.status).toBe('playing');
const cards = practice('one-card');
cards.botProfiles[botsOf(cards)[0]!]!.luck = 1;
expect(cards.start('A')).toBeNull();
expect(cards.status).toBe('lobby');
await Bun.sleep(0);
await Bun.sleep(0);
expect(cards.status).toBe('playing');
expect(cards.game!.shuffles).toBe(1);
const plain = practice('one-card');
plain.botProfiles[botsOf(plain)[0]!]!.luck = 0.05;
expect(plain.start('A')).toBeNull();
expect(plain.status).toBe('playing');
expect(asked).toEqual(['one-card']);
});
});

View File

@@ -0,0 +1,62 @@
/**
* Each computer's level and luck in a room (docs/09-game-engine.md §9.1, docs/06-lobby-rooms.md §12).
* Level 1~60: drawn when the computer is added (any level) or when the host picks a band (쉬움 1~20, 보통 21~40,
* 어려움 41~60). After that it moves a little from game to game but stays near where it started.
*/
import { secureRandom } from '@bg/engine';
import { BOT_BANDS, BOT_LEVEL_MAX, bandOf, type BotPick } from '@bg/shared';
import { hash01, idLevel } from '@bg/games/bots';
export interface BotProfile {
/** What the host chose: 랜덤 (any level) or a band. */
pick: BotPick;
/** The level drawn for that choice; the drift stays around it. */
base: number;
/** The level it plays at now. */
level: number;
/** -1 (아주 나쁨) … 1 (아주 좋음), drawn once when the computer is added. */
luck: number;
/** Games it has started with this base. */
played: number;
}
/** How far a level may move from where it started, and how much in one game. */
export const DRIFT_RANGE = 5;
export const DRIFT_STEP = 2;
const int = (lo: number, hi: number, random: () => number) => lo + Math.floor(random() * (hi - lo + 1));
export function rollLevel(pick: BotPick, random: () => number = secureRandom): number {
const [lo, hi] = pick === 'random' ? [1, BOT_LEVEL_MAX] : BOT_BANDS[pick];
return int(lo, hi, random);
}
export function newBotProfile(random: () => number = secureRandom): BotProfile {
const base = rollLevel('random', random);
return { pick: 'random', base, level: base, luck: random() * 2 - 1, played: 0 };
}
/** The host picked a difficulty: a new level from that range, luck stays. */
export function repick(p: BotProfile, pick: BotPick, random: () => number = secureRandom): BotProfile {
const base = rollLevel(pick, random);
return { ...p, pick, base, level: base, played: 0 };
}
/**
* Before each game after the first: the level moves by at most `DRIFT_STEP`, never more than `DRIFT_RANGE` from where
* it started and never out of that band (a 60 can become 58, never 41).
*/
export function drift(p: BotProfile, random: () => number = secureRandom): BotProfile {
if (p.played === 0) return { ...p, played: 1 };
const [blo, bhi] = BOT_BANDS[bandOf(p.base)];
const lo = Math.max(blo, p.base - DRIFT_RANGE);
const hi = Math.min(bhi, p.base + DRIFT_RANGE);
const level = Math.min(hi, Math.max(lo, p.level + int(-DRIFT_STEP, DRIFT_STEP, random)));
return { ...p, level, played: p.played + 1 };
}
/** Computers saved before rooms kept a profile: level and luck fixed by the id. */
export function profileFromId(bot: string): BotProfile {
const base = idLevel(bot);
return { pick: 'random', base, level: base, luck: hash01(bot, 'luck') * 2 - 1, played: 0 };
}

View File

@@ -1,9 +1,11 @@
/** 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 { SiteSettingsSchema, type SettingsStore } from '../admin/settings';
import { botPace, defaultBotDelay, type BotDelayInput } from './bots';
import { RoomManager } from './manager';
import { Room, type Conn, type RoomSnapshot } from './room';
@@ -88,6 +90,41 @@ describe('bot list', () => {
}
});
test('game speed scales the thinking time, but not a reaction the game timed itself', () => {
const bot = 'bot:1:01J0000000000000000000000';
const r = () => 0.5;
const input = { choices: 4, withPeople: true, bot, followUp: false };
expect(defaultBotDelay(input, r, 3)).toBe(Math.round((2600 * botPace(bot) + 1500) * 3));
expect(defaultBotDelay(input, r, 0.25)).toBe(Math.round((2600 * botPace(bot) + 1500) * 0.25));
expect(defaultBotDelay({ ...input, reactMs: 800 }, r, 3)).toBe(800);
});
test('the admin game speed reaches the computers (×1.5 slower base) and the room view', () => {
let speed = 1 / 16;
const db = openDb(':memory:');
let now = 1_000_000;
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
const settings = { game: () => null, getSite: () => SiteSettingsSchema.parse({ gameSpeed: speed }) } as unknown as SettingsStore;
const manager = new RoomManager({ store: new RoomStore(db), games: GAMES, users, now: () => now, settings });
const play = () => {
const room = manager.createPractice('A', 'omok') as Room;
rooms.push(room);
room.join({ userId: 'A', send: () => {}, close: () => {} }, 'player');
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } });
expect(room.start('A')).toBeNull();
room.act('A', 1, { type: 'place', x: 7, y: 7 });
expect(room.roomView().gameSpeed).toBe(speed);
return room.bots.dueAt! - now;
};
// 1/16: at least the shortest thought (0.49 s) × 1.5 × 16, though never past half the 30 s turn timer.
const slow = play();
expect(slow).toBeGreaterThanOrEqual(11_000);
expect(slow).toBeLessThanOrEqual(15_000);
speed = 16;
// ×16: at most the longest thought (10.4 s) × 1.5 / 16.
expect(play()).toBeLessThanOrEqual(1000);
});
test('thinking never takes more than half of the time left on the turn timer', () => {
const h = harness(undefined, undefined, () => 60 * 60_000);
const room = h.manager.createPractice('A', 'omok') as Room;
@@ -338,6 +375,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();

View File

@@ -3,9 +3,11 @@
* After every state change the room calls `schedule()`: if the game waits on a bot, one action is planned after a
* short human-like pause and played through the room's normal action path (validated, logged as `act`).
*/
import type { AnyGameDefinition } from '@bg/engine';
import { secureRandom, type AnyGameDefinition } from '@bg/engine';
import { isBotId } from '@bg/shared';
import { LIVE_BOT_STRATEGIES, botCandidates, botPace, botPersona, decideBotAction, 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';
export { botPace };
@@ -21,6 +23,12 @@ export interface BotRoom {
log?: (level: 'info' | 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void;
/** Display name of a player (live bots talk about each other by name). */
nameOf?(id: string): string;
/** A computer's level now and the level it started with (docs/09 §9.1); absent = fixed by the id. */
profile?(bot: string): { level: number; base: number };
/** The computers' talk and visible activity with the local model (docs/06 §12.1). */
brain?: BotBrain;
/** Multiplies the computers' thinking time and live games' look intervals (game speed, docs/14 §5); absent = 1. */
timeScale?(): number;
}
/** What a planned computer move looks like, for its thinking time. */
@@ -33,23 +41,31 @@ 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;
}
/**
* Human-like thinking time (ms). A forced move still takes a moment to notice (0.7~1.3 s); a real choice takes longer
* the more moves there are (1.6~3.9 s), and now and then the computer hesitates (+1~3 s). Each bot scales it by its
* own pace, and a follow-up move of the same turn is quicker. When people may act in the same window the computer
* waits 1.5 s more so it never beats a person to a reaction just by being fast.
* waits 1.5 s more so it never beats a person to a reaction just by being fast. `scale` (game speed, `BOT_SLOWDOWN /
* speed`) multiplies the whole thinking time; a reaction the game timed itself (`reactMs`) is never scaled, so who
* calls first stays fair.
*/
export function defaultBotDelay(input: BotDelayInput, random: () => number = Math.random): number {
export function defaultBotDelay(input: BotDelayInput, random: () => number = secureRandom, scale = 1): 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);
if (followUp) ms *= 0.5;
return Math.round(withPeople ? ms + 1500 : ms);
return Math.round((withPeople ? ms + 1500 : ms) * scale);
}
/** At game speed ×1 the computers take this much longer than `defaultBotDelay`'s base times (2026-10-14: a bit slower). */
export const BOT_SLOWDOWN = 1.5;
/** Never use more than this share of the time left on the turn timer for thinking. */
export const BOT_DEADLINE_SHARE = 0.5;
@@ -62,42 +78,93 @@ 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. */
private liveDue = new Map<string, number>();
private liveMemory = new Map<string, Record<string, unknown>>();
private liveGame: unknown = null;
/** A computer is typing / about to move with the model (turn games: one at a time; live games: per computer). */
private busy: string | null = null;
private liveBusy = new Set<string>();
constructor(
private room: BotRoom,
private random: () => number = Math.random,
private delay: (input: BotDelayInput) => number = (input) => defaultBotDelay(input, random),
private random: () => number = secureRandom,
private delay: (input: BotDelayInput) => number = (input) => defaultBotDelay(input, random, room.timeScale?.() ?? 1),
) {}
/** 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) 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;
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();
}
private timeScale(): number {
return this.room.timeScale?.() ?? 1;
}
private liveStrategy(): LiveBotStrategy | null {
return LIVE_BOT_STRATEGIES[this.room.def.id] ?? null;
}
@@ -121,7 +188,7 @@ export class BotDriver {
}
const now = this.room.now();
for (const p of g.players) {
if (isBotId(p) && !this.liveDue.has(p)) this.liveDue.set(p, now + Math.round((300 + this.random() * 1200) * botPace(p)));
if (isBotId(p) && !this.liveDue.has(p)) this.liveDue.set(p, now + Math.round((300 + this.random() * 1200) * botPace(p) * this.timeScale()));
}
const next = Math.min(...this.liveDue.values());
this.dueAt = Number.isFinite(next) ? next : null;
@@ -135,29 +202,66 @@ export class BotDriver {
for (const [bot] of due) {
const g = this.room.game;
if (!g || g.finished || this.room.status !== 'playing') return;
if (this.liveBusy.has(bot)) {
this.liveDue.set(bot, now + 500);
continue;
}
const def = this.room.def;
const memory = this.liveMemory.get(bot) ?? {};
this.liveMemory.set(bot, memory);
const names: Record<string, string> = {};
for (const p of g.players) names[p] = this.room.nameOf?.(p) ?? p;
let decision: { action: unknown; next: number } = { action: null, next: 3000 };
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), 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) });
}
const ms = performance.now() - t0;
if (ms > BOT_SLOW_MS) this.room.log?.('warn', 'slow bot move', { game: def.id, ms: Math.round(ms) });
this.liveDue.set(bot, now + Math.max(100, decision.next));
this.liveDue.set(bot, now + Math.max(100, Math.round(decision.next * this.timeScale())));
if (decision.action == null) continue;
if (!def.validate(g.state, bot, decision.action, { now }).ok) continue; // the moment passed (phase changed); look again later
const brain = this.room.brain;
const say = decision.action as { type?: string; channel?: string; text?: string };
// 라이어 게임's description is typed like a chat line too ("입력 중…" before it appears).
if (brain && (say.type === 'chat' || say.type === 'describe') && brain.enabled()) {
this.typeLive(brain, bot, say as { type: 'chat' | 'describe'; channel: string; text: string }, decision.hint ?? null, names, g);
continue;
}
const err = this.room.run(bot, decision.action);
if (err) this.room.log?.('warn', 'bot action rejected', { game: def.id, action: decision.action, err });
}
this.scheduleLive();
}
/**
* Live chat like a person: the model may say the planned line in the computer's own words, then "입력 중…" for the
* typing time, then it is sent (if it still may be: the phase can end meanwhile).
*/
private typeLive(brain: BotBrain, bot: string, chat: { type: 'chat' | 'describe'; channel: string; text: string }, hint: string | null, names: Record<string, string>, g: unknown): void {
this.liveBusy.add(bot);
const view = this.room.def.view(this.room.game!.state, bot) as { chat?: { channel: string; from: string; text: string }[] };
const recent = (view.chat ?? []).filter((m) => m.channel === chat.channel).slice(-8).map((m) => ({ from: names[m.from] ?? '누군가', text: m.text }));
void (hint ? brain.mafiaLine(bot, hint, chat.text, recent) : Promise.resolve(chat.text))
.catch(() => chat.text)
.then((text) =>
brain.type(bot, text, () => {
const game = this.room.game;
if (!game || game !== g || game.finished) return;
const action = { ...chat, text };
const ok = this.room.def.validate(game.state, bot, action, { now: this.room.now() }).ok;
const err = ok ? this.room.run(bot, action) : this.room.def.validate(game.state, bot, chat, { now: this.room.now() }).ok ? this.room.run(bot, chat) : null;
if (err) this.room.log?.('warn', 'bot chat rejected', { game: this.room.def.id, err });
}),
)
.finally(() => {
this.liveBusy.delete(bot);
});
}
private arm(): void {
if (this.timer) clearTimeout(this.timer);
this.timer = setTimeout(() => this.fire(), Math.max(0, (this.dueAt ?? 0) - this.room.now()));
@@ -171,8 +275,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 };
}
@@ -191,24 +298,53 @@ 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;
try {
action = decideBotAction(def, g.state, next.bot, { now: this.room.now(), random: this.random });
action = decideBotAction(def, g.state, next.bot, { now: this.room.now(), random: this.random, level: this.room.profile?.(next.bot).level ?? idLevel(next.bot) });
} catch (err) {
this.room.log?.('error', 'bot decision failed', { game: def.id, err: String(err) });
action = null;
}
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;
// 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;
void brain
.beforeMove(bot, action, def.view(g.state, bot))
.catch(() => action)
.then((chosen) => {
this.busy = null;
brain.thinking(bot, false);
if (this.room.game !== g || g.finished || this.room.status !== 'playing') return;
const ok = (a: unknown) => def.validate(g.state, bot, a, { now: this.room.now() }).ok;
// The game moved on while it was typing (a timer, someone left): think again.
if (!ok(chosen) && !ok(action)) return this.schedule();
this.acting = bot;
try {
this.playPlanned(bot, ok(chosen) ? chosen : action);
} finally {
this.acting = null;
}
});
return;
}
brain?.thinking(next.bot, false);
this.acting = next.bot;
try {
this.playPlanned(next.bot, action);

View File

@@ -0,0 +1,89 @@
/** 사건 파일 through a real Room: briefing clock, captain passes, report clock, race clock, and views that keep unread texts on the server (docs/games/case-file.md §8.5). */
import { describe, expect, test } from 'bun:test';
import type { ServerMessage } from '@bg/shared';
import { GAMES } from '@bg/games';
import { CASES, type CaseFileOptions, type CaseFileState } from '@bg/games/case-file';
import { openDb } from '../db';
import { Room, type Conn, type RoomConfig } from './room';
import { RoomStore } from './store';
function harness(players: string[], opts: Partial<CaseFileOptions> = {}) {
const db = openDb(':memory:');
const store = new RoomStore(db);
let now = 1_000_000;
const clock = { now: () => now, set: (t: number) => (now = t), advance: (ms: number) => (now += ms) };
const games = { 'case-file': GAMES['case-file']! };
const deps = { store, games, users: { publicUser: (id: string) => ({ id, nickname: id, avatar: null, kind: 'guest' as const }) }, now: clock.now };
const config: RoomConfig = { gameId: 'case-file', options: games['case-file'].optionsSchema.parse(opts), maxPlayers: players.length, visibility: 'private', allowSpectators: true, chatEnabled: true, chatFilter: true, graceSec: 60 };
const room = new Room('room1', '482913', config, players[0]!, deps);
store.insertRoom({ id: 'room1', code: '482913', hostId: players[0]!, gameId: 'case-file', status: 'lobby', visibility: 'private', config, stateJson: '{}', now });
const conns: Record<string, Conn & { msgs: ServerMessage[] }> = {};
for (const p of players) {
const msgs: ServerMessage[] = [];
conns[p] = { userId: p, msgs, send: (m) => msgs.push(m), close: () => {} };
room.join(conns[p], 'player');
}
expect(room.start(players[0]!)).toBeNull();
room.clearTimer();
const state = () => room.game!.state as CaseFileState;
/** Jumps to the current deadline and lets the room fire it. */
const expire = () => {
clock.set(Math.max(clock.now(), room.effectiveDeadline()!));
room.onTimer();
room.clearTimer();
};
let cs = 0;
/** Sends an action like the client and fails on a reject. */
const act = (p: string, a: unknown) => {
const before = conns[p]!.msgs.length;
room.act(p, ++cs, a);
room.clearTimer();
const rej = conns[p]!.msgs.slice(before).find((m) => m.t === 'reject');
if (rej) throw new Error(`${p} ${JSON.stringify(a)} rejected: ${JSON.stringify(rej)}`);
};
return { room, clock, conns, state, expire, act };
}
const allText = (msgs: ServerMessage[]) => JSON.stringify(msgs);
describe('사건 파일 room flow', () => {
test('의뢰 60초 → 수사, 반장 시간 초과는 넘기기만, 보고서 시간 초과 → 채점', () => {
const { room, state, expire, conns, act } = harness(['A', 'B'], { turnSeconds: 60, reportSeconds: 180 });
expect(state().phase).toBe('briefing');
expire();
expect(state().phase).toBe('investigate');
const cap = state().players[state().decider]!.id;
expire();
expect(state().players[state().decider]!.id).not.toBe(cap);
expect(state().investigations.team!.visited).toHaveLength(0);
const now = state().players[state().decider]!.id;
act(now, { type: 'pick', lead: 'c1-03' });
// The read text went out; texts nobody read did not.
const c = CASES.c1;
expect(allText(conns.A!.msgs)).toContain(JSON.stringify(c.leads[2]!.text).slice(1, 40));
expect(allText(conns.B!.msgs)).not.toContain(JSON.stringify(c.leads[10]!.text).slice(1, 40));
expect(allText(conns.B!.msgs)).not.toContain(JSON.stringify(c.solution).slice(1, 40));
const next = state().players[state().decider]!.id;
act(next, { type: 'report' });
expect(state().phase).toBe('report');
act('A', { type: 'answer', q: 'q1', choice: 0 });
expire();
expire();
expect(room.game!.finished).toBe(true);
expect(room.lastResult!.summary).toContain('범인은 강민재였어요');
});
test('따로 겨루기: 전체 시간이 끝나면 모두 보고서, 끝나면 순위', () => {
const { room, state, expire, act } = harness(['A', 'B'], { mode: 'race', raceMinutes: 30, reportSeconds: 180 });
expire();
expect(state().raceEndsAt).not.toBeNull();
act('A', { type: 'pick', lead: 'c1-01' });
expire();
expect(state().phase).toBe('report');
act('B', { type: 'answer', q: 'q1', choice: 0 });
act('B', { type: 'submit' });
expire();
expect(room.game!.finished).toBe(true);
expect(room.lastResult!.ranking).toEqual([['B'], ['A']]);
});
});

View File

@@ -0,0 +1,91 @@
/** 버건디의 성 through a real Room: a practice game against a computer, played from the person's own screen, with turn clocks (docs/games/castles-of-burgundy.md §8.5). */
import { afterEach, describe, expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import type { CobAction, CobState, CobView } from '@bg/games/castles-of-burgundy';
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
import { openDb } from '../db';
import { RoomManager } from './manager';
import type { Room, 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 lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m): m is StateMsg => m.t === 'state').at(-1)?.view ?? null) as CobView | null;
/** What the person presses, read only from their own screen: place > take > anything but ending the turn early. */
function personMove(v: CobView): CobAction | null {
const my = v.my;
if (!my || !my.moves.length) return null;
const rank = (a: CobAction) =>
a.type === 'useDie' ? (a.act.kind === 'place' ? 0 : a.act.kind === 'take' ? 1 : 3) : a.type === 'endTurn' ? 9 : a.type === 'buy' ? 8 : 2;
let best = my.moves.map((a, i) => ({ a, i })).sort((x, y) => rank(x.a) - rank(y.a) || (my.costs[x.i] ?? 0) - (my.costs[y.i] ?? 0) || x.i - y.i)[0]!.a;
if (my.needDiscard) {
if ((best.type === 'useDie' || best.type === 'bonus') && best.act.kind === 'take') best = { ...best, act: { ...best.act, discard: 0 } };
else if ((best.type === 'buy' || best.type === 'depotTake' || best.type === 'soloTrade') && 'tile' in best) best = { ...best, discard: 0 } as CobAction;
}
return best;
}
describe('버건디의 성 room flow', () => {
test('컴퓨터와 연습: 사람은 자기 화면만 보고 두고, 가끔 시간을 넘겨도 끝까지 가요', () => {
const h = harness();
const room = h.manager.createPractice('A', 'castles-of-burgundy') as Room;
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.length).toBeGreaterThan(0);
let cs = 0;
let mine = 0;
let lastTurn = -1;
let skipTurn = false;
for (let i = 0; i < 60_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 v = lastView(a);
if (!v || !v.my) continue;
if (v.turnSeq !== lastTurn) {
lastTurn = v.turnSeq;
skipTurn = v.turnSeq % 7 === 3; // now and then the person lets the clock run out
}
if (skipTurn) continue;
const m = personMove(v);
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 CobState;
expect(s.stage).toBe('finished');
expect(s.log.some((e) => e.t === 'end')).toBe(true);
expect(mine).toBeGreaterThan(40);
const last = lastView(a)!;
expect(last.final!.map((r) => r.player).sort()).toEqual(['A', ...bots].sort());
const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!;
expect(JSON.parse(row.result_json).practice).toBe(true);
}, 60_000);
});

View File

@@ -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();

View File

@@ -0,0 +1,113 @@
/** 젬블로 through a real Room: practice against computers from the person's own screen, and the turn clock (docs/games/gemblo.md §8.5, §10). */
import { afterEach, describe, expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import type { GembloAction, GembloState, GembloView } from '@bg/games/gemblo';
import { legalPlacements, obstaclePlacements } from '@bg/games/gemblo/board';
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 lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m): m is StateMsg => m.t === 'state').at(-1)?.view ?? null) as GembloView | null;
/** What the person does, read only from their own screen: tap the first link point, take the first way it offers. */
function personMove(v: GembloView, me: string): GembloAction | null {
if (v.turnPlayer !== me || v.phase === 'finished') return null;
if (v.phase === 'obstacleDraft') return { type: 'pickObstacle', pieceId: v.obstacle!.pool[0]! };
if (v.phase === 'obstaclePlace') {
const p = obstaclePlacements(v, v.obstacle!.hands[me]!, v.obstacle!.sectorCount, undefined, 1)[0]!;
return { type: 'placeObstacle', pieceId: p.pieceId, orient: p.orient, q: p.q, r: p.r };
}
if (!v.legal) return null;
const c = v.colors[v.turn]!;
// A link point may be one no block left can cover (only the 1-cell block would fit): try the next point.
for (const point of v.legal.bridgePoints) {
const p = legalPlacements(v, c, v.allowFlip, { points: [point] })[0];
if (p) return { type: 'place', pieceId: p.pieceId, orient: p.orient, q: p.q, r: p.r };
}
throw new Error('my turn without a placement');
}
function drive(h: ReturnType<typeof harness>, room: Room, a: ReturnType<ReturnType<typeof harness>['conn']>, play: boolean) {
let cs = 0;
let mine = 0;
for (let i = 0; i < 20_000 && !room.game!.finished; i++) {
h.clock.advance(500);
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 v = lastView(a);
const m = play && v ? personMove(v, 'A') : null;
if (m) {
room.act('A', ++cs, m);
mine++;
}
}
return mine;
}
describe('젬블로 room flow', () => {
test('컴퓨터 1명과 연습: 사람은 자기 화면(이음점 → 놓는 방법)만 보고 끝까지', () => {
const h = harness();
const room = h.manager.createPractice('A', 'gemblo') as Room;
rooms.push(room);
const a = h.conn('A');
room.join(a, 'player');
expect(room.start('A')).toBeNull();
const mine = drive(h, room, a, true);
expect(room.game!.finished).toBe(true);
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
const s = room.game!.state as GembloState;
expect(s.colors).toHaveLength(4); // 2명 = 2색씩
expect(s.placements.filter((p) => p.auto)).toEqual([]);
expect(mine).toBeGreaterThan(10);
const v = lastView(a)!;
expect(v.result!.ranking.flat().sort()).toEqual(['A', ...s.players.filter(isBotId)].sort());
const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!;
expect(JSON.parse(row.result_json).practice).toBe(true);
});
test('5명(장애물 직접 고르기) + 시간 초과만 하는 사람: 자동 배치 두 번 뒤 그 사람 색은 끝나고 게임은 끝까지', () => {
const h = harness();
const r = h.manager.create('A', 'gemblo', 'private');
if (typeof r === 'string') throw new Error(r);
const room = r;
rooms.push(room);
const a = h.conn('A');
room.join(a, 'player');
for (let i = 0; i < 4; i++) expect(room.addBot('A')).toBeNull();
expect(room.configure('A', { options: { ...GAMES.gemblo!.defaultOptions, fivePlayerObstacles: 'draft' } })).toBeNull();
expect(room.start('A')).toBeNull();
expect((room.game!.state as GembloState).phase).toBe('obstacleDraft');
drive(h, room, a, false);
expect(room.game!.finished).toBe(true);
const s = room.game!.state as GembloState;
expect(s.placements.filter((p) => p.kind === 'obstacle').length).toBeGreaterThanOrEqual(13);
const auto = s.placements.filter((p) => p.auto && p.kind === 'play' && s.colors.find((c) => c.color === p.color)?.owner === 'A');
expect(auto).toHaveLength(2);
expect(s.out).toEqual([expect.objectContaining({ playerId: 'A', reason: 'timeLoss' })]);
expect(lastView(a)!.result!.ranking.at(-1)).toEqual(['A']);
});
});

View File

@@ -0,0 +1,150 @@
/** 핫스트릭 through a real Room: races flip on the server clock only, 빨리 보기 needs everyone, practice games finish (docs/games/hot-streak.md §10). */
import { afterEach, describe, expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import type { HotStreakAction, HotStreakState, HotStreakView } from '@bg/games/hot-streak';
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 HotStreakView);
/** What the person presses, read only from their own screen. */
function personMove(v: HotStreakView, n: number): HotStreakAction | null {
const l = v.legal;
if (l.draft) {
const o = l.draft[n % l.draft.length]!;
return { type: 'DRAFT', stack: o.stack, side: n % 3 === 0 ? 'risky' : 'safe' };
}
if (l.double) return { type: 'DOUBLE', index: 0 };
if (l.submit) return { type: 'SUBMIT', cards: l.submit.cards.slice(0, l.submit.count) };
if (l.pot) return { type: 'POT_BET', mascot: 'D', last: false, side: 'NO', doubled: l.pot.doubleRequired ? 'mascot' : null };
if (l.ready) return { type: 'READY' };
return null;
}
function tick(h: ReturnType<typeof harness>, room: Room, ms = 250) {
h.clock.advance(ms);
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();
}
describe('핫스트릭 room flow', () => {
test.each([1, 3])('컴퓨터 %i명과 연습: 사람은 자기 화면만 보고 끝까지, 남이 넣은 카드는 안 보여요', (nBots) => {
const h = harness();
let room: Room;
if (nBots === 1) room = h.manager.createPractice('A', 'hot-streak') as Room;
else {
const r = h.manager.create('A', 'hot-streak', '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 mine = 0;
let seen = 0;
for (let i = 0; i < 60_000 && !room.game!.finished; i++) {
tick(h, room);
const vs = views(a);
for (const v of vs.slice(seen)) {
expect(v.me).toBe('A');
const st = room.game!.state as HotStreakState;
for (const b of bots) for (const c of st.hands[b] ?? []) expect(JSON.stringify(v)).not.toContain(c);
}
seen = vs.length;
const v = vs.at(-1);
const m = v && personMove(v, 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 HotStreakState;
expect(s.results).toHaveLength(3);
expect(s.timeouts.A).toBe(0);
expect(mine).toBeGreaterThan(6);
const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!;
expect(JSON.parse(row.result_json).practice).toBe(true);
});
test('경주는 서버 시계로만 넘어가요: 끊긴 사람이 있어도 2초마다 한 장, 모두 [빨리 보기]면 바로 끝', () => {
const h = harness();
const r = h.manager.create('A', 'hot-streak', 'private');
if (typeof r === 'string') throw new Error(r);
const room = r;
rooms.push(room);
const a = h.conn('A');
const b = h.conn('B');
const c = h.conn('C');
room.join(a, 'player');
room.join(b, 'player');
room.join(c, 'player');
expect(room.start('A')).toBeNull();
let cs = 0;
const st = () => room.game!.state as HotStreakState;
// Everyone plays the betting steps from their own view.
for (let i = 0; i < 400 && st().phase !== 'race'; i++) {
for (const [p, cn] of [['A', a], ['B', b], ['C', c]] as const) {
const v = views(cn).at(-1);
const m = v && personMove(v, i);
if (m) room.act(p, ++cs, m);
}
tick(h, room, 100);
}
expect(st().phase).toBe('race');
// C drops: nothing speeds up (the driver's grace is 0 but cards wait for their time).
room.disconnect(c);
const flipAt = st().race!.nextFlipAt;
expect(room.effectiveDeadline()).toBe(flipAt);
const before = st().race!.processed;
h.clock.advance(flipAt - h.clock.now() - 10);
room.onTimer();
expect(st().race!.processed).toBe(before);
h.clock.advance(10);
room.onTimer();
expect(st().race!.processed).toBe(before + 1);
// Next card two seconds later.
expect(room.effectiveDeadline()).toBe(h.clock.now() + 2000);
// 빨리 보기: A and B agree, C (offline) has not — still running.
room.act('A', ++cs, { type: 'HURRY' });
room.act('B', ++cs, { type: 'HURRY' });
if (st().phase === 'race') {
expect(st().race!.hurry.sort()).toEqual(['A', 'B']);
room.join(c, 'player');
room.act('C', ++cs, { type: 'HURRY' });
}
expect(st().phase).toBe('payout');
expect(st().race!.over).toBe(true);
});
});

View 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: 'describe', 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([]);
});
});

View File

@@ -0,0 +1,18 @@
/** Worker thread for the computers' luck (docs/04 §5.1): plays out candidate shuffles off the rooms' thread. */
import { createSeed, secureRandom } from '@bg/engine';
import { GAMES } from '@bg/games';
import { chooseLuckySeed, type LuckJob } from '@bg/games/bots/luck';
declare const self: Worker;
self.onmessage = (e: MessageEvent<{ id: number; job: LuckJob }>) => {
const { id, job } = e.data;
try {
const def = GAMES[job.gameId];
if (!def) throw new Error(`unknown game ${job.gameId}`);
const { seed, tried } = chooseLuckySeed(def, job, createSeed, secureRandom);
self.postMessage({ id, seed, tried });
} catch (err) {
self.postMessage({ id, error: String(err) });
}
};

View File

@@ -0,0 +1,49 @@
/** The luck worker (docs/04 §5.1): real thread, real play-outs. */
import { expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import { createLuckSeeder } from './luck';
const job = (gameId: string, luck: number) => ({
gameId,
players: ['human', 'bot:1:a'],
options: GAMES[gameId]?.defaultOptions ?? {},
now: Date.now(),
gameNo: 1,
luck: { 'bot:1:a': luck },
levels: { 'bot:1:a': 30 },
budgetMs: 1500,
});
test('plays out the shuffles on a worker thread and returns one of them', async () => {
const seeder = createLuckSeeder();
try {
const [lucky, plain] = await Promise.all([seeder.seed(job('one-card', 1)), seeder.seed(job('one-card', 0))]);
expect(lucky.seed).toHaveLength(8);
expect(lucky.tried).toBe(5);
expect(plain.tried).toBe(1);
expect(lucky.seed.every((w) => Number.isInteger(w) && w >= 0 && w < 2 ** 32)).toBe(true);
} finally {
seeder.stop();
}
}, 20_000);
test('an unknown game or a slow worker falls back to one fresh seed', async () => {
const logs: string[] = [];
const seeder = createLuckSeeder({ log: (_l, msg) => logs.push(msg) });
try {
const r = await seeder.seed(job('nope', 1));
expect(r.tried).toBe(1);
expect(r.seed).toHaveLength(8);
expect(logs).toContain('luck shuffle failed');
} finally {
seeder.stop();
}
const slow = createLuckSeeder({ timeoutMs: 1, log: (_l, msg) => logs.push(msg) });
try {
const r = await slow.seed(job('mahjong', 1));
expect(r.tried).toBe(1);
expect(logs).toContain('luck shuffle timed out');
} finally {
slow.stop();
}
}, 20_000);

View File

@@ -0,0 +1,76 @@
/**
* The rooms' side of the luck worker (docs/04-stability-security.md §5.1). Playing out a few shuffles takes up to a
* couple of seconds for the heaviest games (마작), so it runs on its own thread; the rooms keep running meanwhile.
* One worker, jobs in order. If the worker fails or takes too long, the game starts with one fresh seed (no luck).
*/
import { createSeed, type ChaChaSeed } from '@bg/engine';
import type { LuckJob } from '@bg/games/bots/luck';
type Picked = { seed: ChaChaSeed; tried: number };
export interface LuckSeeder {
seed(job: LuckJob): Promise<Picked>;
stop(): void;
}
export function createLuckSeeder(opts: { timeoutMs?: number; log?: (level: 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void } = {}): LuckSeeder {
const timeoutMs = opts.timeoutMs ?? 8000;
let worker: Worker | null = null;
let nextId = 1;
const pending = new Map<number, { resolve: (p: Picked) => void; timer: ReturnType<typeof setTimeout> }>();
const fallback = (): Picked => ({ seed: createSeed(), tried: 1 });
const settle = (id: number, p: Picked) => {
const job = pending.get(id);
if (!job) return;
pending.delete(id);
clearTimeout(job.timer);
job.resolve(p);
};
const reset = (why: string) => {
opts.log?.('error', 'luck worker failed', { why });
worker?.terminate();
worker = null;
for (const id of [...pending.keys()]) settle(id, fallback());
};
const get = (): Worker => {
if (worker) return worker;
const w = new Worker(new URL('./luck-worker.ts', import.meta.url).href);
w.onmessage = (e: MessageEvent<{ id: number; seed?: ChaChaSeed; tried?: number; error?: string }>) => {
const { id, seed, tried, error } = e.data;
if (error || !seed) {
opts.log?.('warn', 'luck shuffle failed', { error });
settle(id, fallback());
} else settle(id, { seed, tried: tried ?? 1 });
};
w.onerror = (e) => reset(String((e as ErrorEvent).message ?? e));
w.unref();
worker = w;
return w;
};
return {
seed(job) {
return new Promise<Picked>((resolve) => {
const id = nextId++;
const timer = setTimeout(() => {
opts.log?.('warn', 'luck shuffle timed out', { game: job.gameId });
settle(id, fallback());
}, timeoutMs);
pending.set(id, { resolve, timer });
try {
get().postMessage({ id, job });
} catch (err) {
reset(String(err));
}
});
},
stop() {
worker?.terminate();
worker = null;
for (const id of [...pending.keys()]) settle(id, fallback());
},
};
}

View File

@@ -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,
@@ -57,8 +57,10 @@ describe('마피아 room flow', () => {
expect(all).not.toContain(`"role":"mafia"`);
}
// Rate limit (validate gets the server clock), and the system-only phase timer cannot be sent by clients.
room.act(mafia, 2, { type: 'chat', channel: 'mafia', text: '또' });
expect(conns[mafia]!.msgs.at(-1)).toEqual({ t: 'reject', cs: 2, reason: '조금 천천히 보내 주세요.' });
// No pace limit: a long run of lines in the same instant all goes through.
for (let i = 0; i < 20; i++) room.act(mafia, 10 + i, { type: 'chat', channel: 'mafia', text: `연달아 ${i}` });
expect(lastView(mafia).chat.filter((c) => c.text.startsWith('연달아')).length).toBe(20);
expect(conns[mafia]!.msgs.some((m) => m.t === 'reject')).toBe(false);
room.act(town[0]!, 3, { type: 'phaseTimeout' });
expect(conns[town[0]!]!.msgs.at(-1)).toEqual({ t: 'reject', cs: 3, reason: '잘못된 요청이에요.' });
expect(state().phase.kind).toBe('night');
@@ -67,4 +69,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');
});
});

View 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);
});
});

View File

@@ -1,6 +1,6 @@
/** Creates, finds, restores and garbage-collects rooms (docs/06 §11, docs/04 §3). */
import { ulid } from 'ulid';
import type { AnyGameDefinition } from '@bg/engine';
import { secureRandom, type AnyGameDefinition } from '@bg/engine';
import { PRACTICE_PLAYERS, botsAllowed, isAllowedRoomCode, isBotId, type PublicUser } from '@bg/shared';
import { Room, type RoomConfig, type RoomDeps, type RoomSnapshot } from './room';
import type { RoomStore } from './store';
@@ -25,6 +25,12 @@ export interface ManagerDeps {
random?: () => number;
settings?: SettingsStore;
botDelay?: RoomDeps['botDelay'];
/** Local language model shared by every room's computers. */
ai?: RoomDeps['ai'];
aiSleep?: RoomDeps['aiSleep'];
aiRandom?: RoomDeps['aiRandom'];
/** Shuffles for the computers' luck (docs/04 §5.1); absent = one fresh seed per game. */
luckSeed?: RoomDeps['luckSeed'];
/** When the user's last socket to the site closed; null while the site is open somewhere (the gateway knows). */
offlineSince?: (userId: string) => number | null;
}
@@ -49,6 +55,10 @@ export class RoomManager {
log: this.deps.log,
settings: this.deps.settings,
botDelay: this.deps.botDelay,
ai: this.deps.ai,
aiSleep: this.deps.aiSleep,
aiRandom: this.deps.aiRandom,
luckSeed: this.deps.luckSeed,
onEmpty: (room, why) => {
// The last person left on purpose and nobody holds a seat (only computers, or nobody joined): close it now.
if (why === 'leave' && this.byCode.get(room.code) === room && !room.hasPeopleSeated()) this.close(room);
@@ -73,7 +83,7 @@ export class RoomManager {
}
private newCode(): string {
const rand = this.deps.random ?? Math.random;
const rand = this.deps.random ?? secureRandom;
for (let i = 0; i < 200; i++) {
const code = String(Math.floor(rand() * 1_000_000)).padStart(6, '0');
if (!isAllowedRoomCode(code) || this.byCode.has(code)) continue;
@@ -105,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();

View File

@@ -0,0 +1,120 @@
/** 지뢰찾기 through a real Room: a practice race against a computer, mines never reach my screen, away players (docs/games/minesweeper.md §8.5). */
import { afterEach, describe, expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import type { MinesweeperState, MinesweeperView } from '@bg/games/minesweeper';
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 MinesweeperView;
describe('지뢰찾기 room flow', () => {
test('컴퓨터와 연습: 사람은 안전한 칸을 하나씩 열고, 컴퓨터도 자기 판을 풀어 끝까지 가요. 내 화면에는 지뢰 위치가 없어요', () => {
const h = harness();
const room = h.manager.createPractice('A', 'minesweeper') 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;
const s = () => room.game!.state as MinesweeperState;
for (let i = 0; i < 4 * 900 && !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 v = lastView(a);
if (v.board && v.phase === 'playing' && v.seats.find((x) => x.id === 'A')!.status === 'playing') expect(v.board.cells).not.toMatch(/[*!x]/);
// The person opens the first closed cell next to an opened 0-region every 2 s… or gives up after 60 s.
if (i % 8 === 0 && v.phase === 'playing' && v.board && v.seats.find((x) => x.id === 'A')!.status === 'playing') {
if (h.clock.now() - v.countdownEndsAt > 60_000) room.act('A', ++cs, { type: 'stop' });
else {
const k = [...v.board.cells].findIndex((ch, j) => ch === '#' && s().puzzle.field[j] !== '*');
if (k >= 0) room.act('A', ++cs, { type: 'open', i: k });
}
}
}
expect(room.game!.finished).toBe(true);
expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0);
expect(['solved', 'failed']).toContain(s().status[bot]!);
expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort());
});
test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => {
const h = harness();
const r = h.manager.create('A', 'minesweeper', '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: { level: 'beginner', timeLimitSec: 180 } })).toBeNull();
expect(room.start('A')).toBeNull();
h.clock.advance(3000);
room.onTimer();
const s = () => room.game!.state as MinesweeperState;
expect(s().phase).toBe('playing');
room.disconnect(b);
expect(room.effectiveDeadline()).toBe(s().endsAt);
h.clock.advance(70_000);
room.onTimer();
expect(s().status.B).toBe('playing');
h.clock.advance(s().endsAt! - h.clock.now());
room.onTimer();
expect(room.game!.finished).toBe(true);
expect(s().final!.endReason).toBe('time');
});
test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => {
const h = harness();
const r = h.manager.create('A', 'minesweeper', '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: { level: 'beginner', timeLimitSec: null } })).toBeNull();
expect(room.start('A')).toBeNull();
h.clock.advance(3000);
room.onTimer();
const s = () => room.game!.state as MinesweeperState;
expect(room.effectiveDeadline()).toBeNull();
room.disconnect(b);
const d = room.effectiveDeadline()!;
h.clock.advance(d - h.clock.now());
room.onTimer();
expect(s().status.B).toBe('done');
expect(room.effectiveDeadline()).toBeNull();
room.act('A', 1, { type: 'stop' });
expect(room.game!.finished).toBe(true);
});
});

View File

@@ -0,0 +1,118 @@
/** 네모네모 로직 through a real Room: a practice race against a computer, the answer never reaches my screen, away players (docs/games/nonogram.md §8). */
import { afterEach, describe, expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import type { NonogramState, NonogramView } from '@bg/games/nonogram';
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 NonogramView;
function twoPlayerRoom(h: ReturnType<typeof harness>, timeLimitSec: number | null) {
const r = h.manager.create('A', 'nonogram', '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: { size: 5, hints: true, timeLimitSec } })).toBeNull();
expect(room.start('A')).toBeNull();
h.clock.advance(3000);
room.onTimer();
return { room, a, b, s: () => room.game!.state as NonogramState };
}
describe('nonogram · 네모네모 로직 room flow', () => {
test('컴퓨터와 연습: 사람은 한 줄씩 칠하고, 컴퓨터도 자기 판을 풀어 끝까지 가요. 끝내기 전 내 화면에는 답이 없어요', () => {
const h = harness();
const room = h.manager.createPractice('A', 'nonogram') 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 row = 0;
const s = () => room.game!.state as NonogramState;
for (let i = 0; i < 4 * 1500 && !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 v = lastView(a);
const mine = v.seats.find((x) => x.id === 'A')!;
if (v.board && mine.status === 'playing') {
expect(v.board.answer).toBeNull();
expect(JSON.stringify(v)).not.toContain(s().puzzle.solution);
}
// The person fills one row of the answer every 20 s.
if (i % 80 === 0 && v.phase === 'playing' && v.board && mine.status === 'playing' && row < v.board.size) {
const n = v.board.size;
const cells = Array.from({ length: n }, (_, c) => row * n + c).filter((k) => s().puzzle.solution[k] === '#');
room.act('A', ++cs, { type: 'paint', cells, value: 1 });
row++;
}
}
expect(room.game!.finished).toBe(true);
expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0);
expect(s().status.A).toBe('solved');
expect(s().status[bot]).toBe('solved');
const v = lastView(a);
expect(v.result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort());
expect(v.board!.answer!.name).toBe(s().puzzle.name);
});
test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => {
const h = harness();
const { room, b, s } = twoPlayerRoom(h, 300);
expect(s().phase).toBe('playing');
room.disconnect(b);
expect(room.effectiveDeadline()).toBe(s().endsAt);
h.clock.advance(70_000);
room.onTimer();
expect(s().status.B).toBe('playing');
h.clock.advance(s().endsAt! - h.clock.now());
room.onTimer();
expect(room.game!.finished).toBe(true);
expect(s().final!.endReason).toBe('time');
});
test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => {
const h = harness();
const { room, b, s } = twoPlayerRoom(h, null);
expect(room.effectiveDeadline()).toBeNull();
room.disconnect(b);
const d = room.effectiveDeadline()!;
h.clock.advance(d - h.clock.now());
room.onTimer();
expect(s().status.B).toBe('done');
expect(room.effectiveDeadline()).toBeNull();
room.act('A', 1, { type: 'stop' });
expect(room.game!.finished).toBe(true);
});
});

View File

@@ -10,7 +10,7 @@ import { GAMES } from '@bg/games';
import { openDb } from '../db';
import { Room, type Conn, type RoomConfig } from './room';
import { RoomStore } from './store';
import { Replays, rebuildGame, type ReplayInput } from './replay';
import { Replays, rebuildGame, sameOutcome, type ReplayInput } from './replay';
const json = (v: unknown) => JSON.parse(JSON.stringify(v));
@@ -262,6 +262,24 @@ describe('replay: access and edge cases', () => {
expect(await new Replays(db, GAMES, users).get(pk, 'A')).toMatchObject({ ok: false, status: 410 });
});
test('practice games (marked "practice") and games recorded before final scores existed are replayable', async () => {
const { db, room, users } = omokRoom();
room.act('A', 1, { type: 'place', x: 7, y: 7 });
room.leave('B');
const pk = room.game!.gamePk;
const stored = JSON.parse(db.query<{ result_json: string }, [string]>('SELECT result_json FROM games WHERE id = ?').get(pk)!.result_json);
// As the store writes a game played with computers.
db.query('UPDATE games SET result_json = ? WHERE id = ?').run(JSON.stringify({ ...stored, practice: true }), pk);
const practice = await new Replays(db, GAMES, users).get(pk, 'A');
expect(practice.ok).toBe(true);
// A scored game recorded without scoreText gets it from the rebuilt game; a changed outcome still fails.
const scored = { ...GAMES, omok: { ...GAMES.omok!, result: (st: unknown) => { const r = GAMES.omok!.result(st); return r && { ...r, scoreText: { A: '1점', B: '0점' } }; } } };
const old = await new Replays(db, scored, users).get(pk, 'A');
if (!old.ok) throw new Error(old.error);
expect((JSON.parse(old.body) as ReplayData).result.scoreText).toEqual({ A: '1점', B: '0점' });
expect(sameOutcome({ ranking: [['A'], ['B']], summary: 'x', reason: 'normal' }, { ranking: [['B'], ['A']], summary: 'x', reason: 'normal' })).toBe(false);
});
test('my games list: newest first, paged, with ranks and nicknames', async () => {
const { db, room, clock, users } = omokRoom();
room.act('A', 1, { type: 'place', x: 7, y: 7 });

View File

@@ -41,6 +41,20 @@ function* replaySteps(def: AnyGameDefinition, input: ReplayInput): Generator<Ste
}
}
/**
* Did the rebuilt game end the way it was recorded? Compares the outcome (ranking, scores, reason, summary), not
* labels added around it: the store marks practice games (`practice`), and `scoreText` is display wording that games
* recorded before 2026-10-11 don't have. (Comparing the raw JSON made every practice game and every older scored
* game "not replayable".)
*/
export function sameOutcome(rebuilt: GameResult, stored: GameResult): boolean {
const core = (r: GameResult) => {
const { practice: _p, scoreText: _t, ...rest } = r as GameResult & { practice?: boolean };
return JSON.stringify(rest);
};
return core(rebuilt) === core(stored);
}
/** Final state of a rebuilt game. */
export function rebuildGame(def: AnyGameDefinition, input: ReplayInput): unknown {
let state: unknown;
@@ -233,10 +247,12 @@ export class Replays {
return { ok: false, status: 410, error: '이 게임은 다시 볼 수 없어요.' };
}
// The rebuilt game must end exactly as recorded; otherwise the replay would show a different game.
const result = JSON.parse(g.result_json) as GameResult;
const stored = JSON.parse(g.result_json) as GameResult;
const rebuilt = def.result(built.final);
const matches = g.end_reason === 'void' ? rebuilt === null : JSON.stringify(rebuilt) === g.result_json;
const matches = g.end_reason === 'void' ? rebuilt === null : !!rebuilt && sameOutcome(rebuilt, stored);
if (!matches) return { ok: false, status: 410, error: '이 게임은 다시 볼 수 없어요.' };
// Games recorded before the result screen showed final scores get them from the rebuilt game.
const result: GameResult = rebuilt?.scoreText && !stored.scoreText ? { ...stored, scoreText: rebuilt.scoreText } : stored;
const ids = this.idMap(start.players, seats.map((s) => s.user_id));
const players: Record<string, PublicUser> = {};

View File

@@ -61,6 +61,86 @@ describe('Room timers', () => {
expect((room.game!.state as any).moves[0].auto).toBe(true);
});
test('a turn clock starts when the player\'s screen has finished animating (settled), not before', () => {
const { room, clock, conn } = harness();
const a = conn('A');
const b = conn('B');
room.join(a, 'player');
room.join(b, 'player');
room.configure('A', { options: { colorAssignment: 'hostBlack', timeControl: { kind: 'perMove', perMoveSec: 10 } } });
expect(room.start('A')).toBeNull();
room.clearTimer();
const base = clock.now() + 10_000;
// A screen that never reported keeps the old clock (pages from before this change, computers).
expect(room.effectiveDeadline()).toBe(base);
// A's screen finishes the opening 1.5 s later: A's clock is 1.5 s longer, and everyone is told the new deadline.
clock.advance(1_500);
room.settled('A', room.seq);
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base + 1_500);
expect(b.msgs.at(-1)).toEqual({ t: 'deadline', deadline: base + 1_500 });
clock.advance(10_000 - 1);
room.onTimer();
room.clearTimer();
expect((room.game!.state as any).moves).toHaveLength(0);
clock.advance(1);
room.onTimer();
room.clearTimer();
expect((room.game!.state as any).moves).toHaveLength(1);
// Next state, B to move: a late report for an older state counts nothing, and B (who never reported) keeps the plain clock.
const seq = room.seq;
const base2 = clock.now() + 10_000;
room.settled('A', seq - 1);
expect(room.effectiveDeadline()).toBe(base2); // B is to move and B never reported: B's clock is unchanged
room.settled('B', seq);
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base2);
});
test('a player who reported once but not yet for this state: the timer waits for the screen (at most 15 s at ×1)', () => {
const { room, clock, conn } = harness();
room.join(conn('A'), 'player');
room.join(conn('B'), 'player');
room.configure('A', { options: { colorAssignment: 'hostBlack', timeControl: { kind: 'perMove', perMoveSec: 10 } } });
room.start('A');
room.settled('A', room.seq);
room.settled('B', room.seq);
room.clearTimer();
// A plays; B (to move) has not reported this new state yet
clock.advance(100); // a moment later (a new step has a new clock)
room.act('A', 1, (room.def.legalActions!(room.game!.state, 'A') as unknown[])[0]);
room.clearTimer();
const base = clock.now() + 10_000;
expect(room.effectiveDeadline()).toBe(base + 15_000);
clock.advance(2_000);
room.settled('B', room.seq);
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base + 2_000);
});
test('a deadline moved by a screen that reported before is told to every client (omok)', () => {
const { room, clock, conn } = harness();
const a = conn('A');
const b = conn('B');
room.join(a, 'player');
room.join(b, 'player');
room.configure('A', { options: { colorAssignment: 'hostBlack', timeControl: { kind: 'perMove', perMoveSec: 10 } } });
room.start('A');
room.settled('A', room.seq);
room.settled('B', room.seq);
clock.advance(100); // a moment later (a new step has a new clock)
room.act('A', 1, (room.def.legalActions!(room.game!.state, 'A') as unknown[])[0]);
room.clearTimer();
const base = clock.now() + 10_000;
const sent = b.msgs.filter((m) => m.t === 'state').at(-1) as { deadline: number };
expect(sent.deadline).toBe(base);
clock.advance(2_000);
room.settled('B', room.seq);
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base + 2_000);
for (const c of [a, b]) expect(c.msgs.at(-1)).toEqual({ t: 'deadline', deadline: base + 2_000 });
});
test('disconnected player is auto-acted after the grace period, not before the turn deadline rules', () => {
const { room, clock, conn } = harness();
const a = conn('A');
@@ -226,3 +306,167 @@ describe('윷놀이 room rules', () => {
expect(st.view.turnSeq).toBe((room.game!.state as any).turnSeq);
});
});
describe('Room chat (2026-10-13)', () => {
test('no pace limit: any number of lines in the same instant all go through, in order', () => {
const { room, conn } = harness();
const a = conn('A');
const b = conn('B');
room.join(a, 'player');
room.join(b, 'player');
const lines = Array.from({ length: 30 }, (_, i) => `줄 ${i}`);
for (const t of lines) expect(room.chat('A', t)).toBeNull();
expect(b.msgs.filter((m) => m.t === 'chat').map((m) => (m as { text: string }).text)).toEqual(lines);
});
test('lines sent before joining come back marked as replay; live lines are not', () => {
const { room, conn } = harness();
const a = conn('A');
room.join(a, 'player');
room.chat('A', '먼저 한 말');
const b = conn('B');
room.join(b, 'player');
room.chat('A', '지금 한 말');
const got = b.msgs.filter((m) => m.t === 'chat').map((m) => [(m as { text: string }).text, (m as { replay?: true }).replay ?? false]);
expect(got).toEqual([
['먼저 한 말', true],
['지금 한 말', false],
]);
expect((a.msgs.find((m) => m.t === 'chat') as { replay?: true }).replay).toBeUndefined();
});
test('typing at a person\'s pace (a line every 0.4 s) never waits', () => {
const { room, clock, conn } = harness();
room.join(conn('A'), 'player');
for (let i = 0; i < 30; i++) {
expect(room.chat('A', `줄 ${i}`)).toBeNull();
clock.advance(400);
}
});
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);
});
});
describe('Room clocks after the animation (shared steps)', () => {
// Like 라이어 게임's last guess: everybody votes, then only the liar (B) answers, while the room times a stand-in (A).
const guess: AnyGameDefinition = {
id: 'guess',
nameKo: '맞히기',
minPlayers: 2,
maxPlayers: 2,
stateVersion: 1,
defaultOptions: {},
optionsSchema: z.object({}),
actionSchema: z.object({ type: z.enum(['go', 'chat']) }),
setup: ({ players, now }) => ({ players, step: 'vote', deadlineAt: now + 10_000, chats: 0 }),
validate: () => ({ ok: true }),
apply: (s: any, _p, a: any, { now }) => ({ state: a.type === 'go' ? { ...s, step: 'guess', deadlineAt: now + 10_000 } : { ...s, chats: s.chats + 1 }, events: [] }),
view: (s) => s,
activePlayers: (s: any) => (s.step === 'guess' ? [s.players[1]] : s.players),
timeoutPlayers: (s: any) => (s.step === 'guess' ? [s.players[0]] : s.players),
deadline: (s: any) => s.deadlineAt,
onTimeout: () => ({ type: 'chat' }),
result: () => null,
};
test('the stand-in\'s clock waits for the real answerer\'s screen, and a chat line keeps the time given', () => {
const { room, clock, conn } = harness({ guess });
const a = conn('A');
const b = conn('B');
room.join(a, 'player');
room.join(b, 'player');
room.start('A');
room.settled('A', room.seq);
room.settled('B', room.seq);
clock.advance(100); // a moment later (a new step has a new clock)
room.act('A', 1, { type: 'go' }); // → only B answers now, A is the timed stand-in
room.clearTimer();
const base = clock.now() + 10_000;
clock.advance(1_000);
room.settled('A', room.seq); // A's screen is quick: that must not start B's clock
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base + 15_000);
clock.advance(5_000);
room.settled('B', room.seq); // B's screen took 6 s
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base + 6_000);
expect(b.msgs.at(-1)).toEqual({ t: 'deadline', deadline: base + 6_000 });
// A chat line in the same step keeps B's 6 s.
clock.advance(1_000);
room.act('A', 2, { type: 'chat' });
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base + 6_000);
expect((b.msgs.filter((m) => m.t === 'state').at(-1) as { deadline: number }).deadline).toBe(base + 6_000);
room.settled('B', room.seq);
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base + 6_000);
// B still gets the whole 10 s from when the screen settled: nothing fires a moment before that.
clock.advance(base + 6_000 - clock.now() - 1);
room.onTimer();
room.clearTimer();
expect((room.game!.state as any).chats).toBe(1);
});
// A re-vote: A and B both vote under one shared clock that the room times through A.
const revote: AnyGameDefinition = {
...guess,
id: 'revote',
actionSchema: z.object({ type: z.enum(['go', 'vote', 'chat']) }),
setup: ({ players, now }) => ({ players, step: 'start', deadlineAt: now + 10_000, voted: [] as string[], chats: 0 }),
apply: (s: any, p, a: any, { now }) => ({
state: a.type === 'go' ? { ...s, step: 'vote', deadlineAt: now + 10_000 } : a.type === 'vote' ? { ...s, voted: [...s.voted, p] } : { ...s, chats: s.chats + 1 },
events: [],
}),
activePlayers: (s: any) => (s.step === 'vote' ? s.players.filter((p: string) => !s.voted.includes(p)) : s.players),
timeoutPlayers: (s: any) => (s.step === 'vote' ? [s.players[0]] : s.players),
};
test('a shared vote: the clock waits for the slowest voter\'s screen, and someone voting keeps that time', () => {
const { room, clock, conn } = harness({ revote });
const a = conn('A');
const b = conn('B');
room.join(a, 'player');
room.join(b, 'player');
room.start('A');
room.settled('A', room.seq);
room.settled('B', room.seq);
clock.advance(100); // a moment later (a new step has a new clock)
room.act('A', 1, { type: 'go' });
room.clearTimer();
const base = clock.now() + 10_000;
clock.advance(220);
room.settled('A', room.seq); // A (also the timed stand-in) is done in 0.22 s …
clock.advance(5_780);
room.settled('B', room.seq); // … B only after 6 s: the shared clock gives everybody those 6 s
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base + 6_000);
expect(a.msgs.at(-1)).toEqual({ t: 'deadline', deadline: base + 6_000 });
// A votes: only B is left to answer, same clock: still 6 s more.
room.act('A', 2, { type: 'vote' });
room.clearTimer();
expect(room.effectiveDeadline()).toBe(base + 6_000);
expect((b.msgs.filter((m) => m.t === 'state').at(-1) as { deadline: number }).deadline).toBe(base + 6_000);
});
});

View File

@@ -3,10 +3,15 @@
* All mutations run on the single JS thread, so a room never sees concurrent updates.
*/
import { ulid } from 'ulid';
import { SeededRng, createSeed, seedToHex, type AnyGameDefinition, type GameResult, type RngState } from '@bg/engine';
import { botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared';
import { SeededRng, createSeed, secureRandom, seedToHex, type AnyGameDefinition, type ChaChaSeed, type GameResult, type RngState } from '@bg/engine';
import { botChatRequired, clampChatSound, clampGameSpeed, 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';
import { BotDriver, type BotDelayInput } from './bots';
import { BOT_SLOWDOWN, BotDriver, type BotDelayInput } from './bots';
import { drift, newBotProfile, profileFromId, repick, type BotProfile } from './bot-profile';
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';
@@ -24,6 +29,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;
}
@@ -52,6 +59,10 @@ interface GameSlot {
finished: boolean;
/** After a restore, deadlines are not enforced before this time (docs/04 §3.3). */
deadlineFloor: number | null;
/** Each computer's level and luck in this game (shown in the fairness check afterwards). */
bots?: Record<string, { level: number; luck: number }>;
/** Shuffles tried for the computers' luck (docs/04 §5.1); 1 or absent = the first one. */
shuffles?: number;
}
/** Shape persisted to room_state.state_json. */
@@ -68,6 +79,8 @@ export interface RoomSnapshot {
lastResult: GameResult | null;
game: GameSlot | null;
joinedAt: Record<string, number>;
/** Computers' level and luck (absent in rooms saved before 2026-10-11: then fixed by the bot id). */
bots?: Record<string, BotProfile>;
}
export interface RoomDeps {
@@ -83,12 +96,30 @@ export interface RoomDeps {
settings?: { game(id: string): EffectiveGame | null; getSite(): SiteSettings };
/** Computer players' thinking time (ms) for a decision with `choices` options; tests may pin it. */
botDelay?: (input: BotDelayInput) => number;
/** Local language model for the computers' talk and play-like-people behaviour (docs/06 §12.1); null = off. */
ai?: Llm | null;
/** Waiting inside the computers' talk (typing time); tests may make it instant. */
aiSleep?: (ms: number) => Promise<void>;
/** Dice for the computers' talk (whether to speak now); tests may pin it. */
aiRandom?: () => number;
/**
* Tries shuffles for the computers' luck off the main thread (docs/04 §5.1). Absent (tests): every game starts at
* once with one fresh seed.
*/
luckSeed?: (job: LuckJob) => Promise<{ seed: ChaChaSeed; tried: number }>;
}
const CHAT_HISTORY = 30;
/** Time the luck worker may spend on more shuffles (the first is always played out), docs/04 §5.1. */
export const LUCK_BUDGET_MS = 1500;
const ERROR_LIMIT = 3;
/** Streaming actions (drawing) are logged in batches: at most this long between snapshot writes. */
const STREAM_FLUSH_MS = 1000;
/**
* Longest a player's clock waits for their screen to finish animating a change (ms at game speed ×1 before the
* shared 1.5× slowdown; scaled like the animations). A screen that never reports (an old tab, a hidden tab) costs at most this.
*/
export const REVEAL_MAX_MS = 10_000;
export class Room {
status: 'lobby' | 'playing' | 'finished' | 'paused' | 'broken' = 'lobby';
@@ -109,6 +140,12 @@ export class Room {
lastSeed: string | null = null;
lastResult: GameResult | null = null;
game: GameSlot | null = null;
/** Computers' level and luck (docs/09 §9.1), by bot id. */
botProfiles: Record<string, BotProfile> = {};
/** The computers' shuffles are being tried; the game starts when they're done. */
starting = false;
/** Shut down or closed: late callbacks (the luck worker) must not touch it. */
private closed = false;
chatLog: Extract<ServerMessage, { t: 'chat' }>[] = [];
lastActiveAt: number;
/** When the last connection went away (null while someone is connected). */
@@ -119,10 +156,24 @@ export class Room {
private flushTimer: ReturnType<typeof setTimeout> | null = null;
private recentCs = new Map<string, number[]>();
private lastChatAt = new Map<string, number>();
/** When each person last said they were typing (to drop repeats within a second). */
private typingAt = new Map<string, number>();
private consecutiveErrors = 0;
/**
* The last game state change and when each player's screen finished animating it (client `settled`). A player's
* clock starts then, so a choice shown after the animation still gets its full time (`revealExtra`).
*/
private reveal: { seq: number; at: number; done: Map<string, number>; key: string } | null = null;
/** The deadline last sent to the clients (state / deadline messages), so a moved deadline is always told. */
private sentDeadline: number | null = null;
/** Players whose screens report `settled` (pages from before 2026-11-08 don't: their clocks run as before). */
private settles = new Set<string>();
private readonly now: () => number;
/** Plays the computer players' moves (docs/06 §12). */
readonly bots: BotDriver;
/** The computers' talk and visible activity with the local model (docs/06 §12.1). */
readonly brain: BotBrain;
private botActivity = new Map<string, BotActivity>();
constructor(
readonly id: string,
@@ -137,6 +188,33 @@ export class Room {
this.lastActiveAt = this.now();
this.emptySince = this.now();
const room = this;
this.brain = new BotBrain(
{
gameId: () => this.config.gameId,
gameName: () => this.def.nameKo,
nameOf: (id) => this.nick(id),
humans: () => (this.game && !this.game.finished ? this.game.players : this.seatedIds()).filter((u) => !isBotId(u)),
bots: () => (this.game && !this.game.finished ? this.game.players : this.seatedIds()).filter(isBotId),
playing: () => this.status === 'playing',
roomChat: (bot, text) => {
this.chat(bot, text);
},
setActivity: (bot, a) => {
if ((this.botActivity.get(bot) ?? null) === a) return;
if (a) this.botActivity.set(bot, a);
else this.botActivity.delete(bot);
this.broadcastRoom();
},
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,
deps.aiSleep,
);
this.bots = new BotDriver(
{
get status() {
@@ -156,12 +234,20 @@ export class Room {
},
log: deps.log,
nameOf: (id) => this.deps.users.publicUser(id)?.nickname ?? '누군가',
profile: (bot) => this.profile(bot),
brain: this.brain,
timeScale: () => BOT_SLOWDOWN / this.gameSpeed(),
},
Math.random,
secureRandom,
deps.botDelay,
);
}
/** 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}`);
@@ -253,6 +339,7 @@ export class Room {
lastResult: this.lastResult,
game: this.game,
joinedAt,
bots: this.botProfiles,
};
}
@@ -267,6 +354,7 @@ export class Room {
room.lastSeed = snap.lastSeed;
room.lastResult = snap.lastResult;
room.game = snap.game;
room.botProfiles = snap.bots ?? {};
const now = room.now();
for (const s of room.seats) {
// Computer players have no connection (and so no reconnect grace period).
@@ -281,7 +369,7 @@ export class Room {
}
// 30s to reconnect, plus up to 30s jitter so thousands of restored rooms don't all time out
// in the same instant (thundering herd after a restart, docs/04 §3).
room.game.deadlineFloor = now + 30_000 + Math.floor(Math.random() * 30_000);
room.game.deadlineFloor = now + 30_000 + Math.floor(secureRandom() * 30_000);
room.scheduleTimer();
}
return room;
@@ -349,6 +437,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,
@@ -359,6 +448,13 @@ export class Room {
lockedOptions: this.deps.settings?.game(this.config.gameId)?.lockedOptions ?? [],
lastSeed: this.lastSeed,
lastGamePk: this.game?.finished ? this.game.gamePk : null,
...(this.botActivity.size ? { botActivity: Object.fromEntries(this.botActivity) } : {}),
...(this.hasBots() ? { botPicks: Object.fromEntries(this.seatedIds().filter(isBotId).map((b) => [b, this.profile(b).pick])) } : {}),
...(this.starting ? { starting: true } : {}),
// Levels are revealed only once the game is over (fairness check).
...(this.game?.finished && this.game.bots ? { lastBots: this.game.bots, lastShuffles: this.game.shuffles ?? 1 } : {}),
gameSpeed: this.gameSpeed(),
chatSound: clampChatSound(this.deps.settings?.getSite().chatSound),
};
}
@@ -380,7 +476,7 @@ export class Room {
view,
events: [],
active: this.game.finished ? [] : def.activePlayers(this.game.state),
deadline: this.game.finished ? null : this.effectiveDeadline(),
deadline: (this.sentDeadline = this.game.finished ? null : this.publicDeadline()),
...(cs !== undefined ? { cs } : {}),
};
}
@@ -392,6 +488,10 @@ export class Room {
private broadcastState(events: unknown[], actor?: string, cs?: number): void {
if (!this.game) return;
// A change that leaves the step as it was (a chat line, a move inside the same shared clock) keeps the time
// already given for the step's animation; a new step (new clock, new players to act) starts a new reveal.
const key = this.revealKey();
if (!this.reveal || this.reveal.key !== key) this.reveal = { seq: this.seq, at: this.now(), done: new Map(), key };
let spectatorMsg: ServerMessage | null = null;
for (const c of this.conns.values()) {
let msg: ServerMessage | null;
@@ -449,7 +549,7 @@ export class Room {
const st = this.stateMessage(u, undefined, true);
if (st) conn.send(st);
if (this.status === 'finished' && this.lastResult) conn.send({ t: 'result', seq: this.seq, result: this.lastResult });
for (const m of this.chatLog) conn.send(m);
for (const m of this.chatLog) conn.send({ ...m, replay: true });
this.scheduleTimer();
return null;
}
@@ -462,6 +562,9 @@ export class Room {
const u = conn.userId;
if (this.conns.get(u) !== conn) return;
if (this.spectators.has(u)) return this.disconnect(conn);
// Alone in the lobby: nobody to come back to, so leaving the page (뒤로가기, 홈) leaves the room and the empty room
// closes now instead of lingering (2026-10-14). A game (running, or its result: 다시 보기 comes back) keeps the seat.
if (this.status === 'lobby' && this.conns.size === 1 && !this.seatedIds().some((x) => x !== u && !isBotId(x) && !this.leftDuringGame.has(x))) return this.leave(u);
this.conns.delete(u);
this.detached.set(u, conn);
if (this.conns.size === 0) this.becameEmpty('disconnect');
@@ -537,9 +640,20 @@ export class Room {
// ---------------------------------------------------------------- lobby commands
private requireLobby(): string | null {
if (this.starting) return '게임을 준비하고 있어요.';
return this.status === 'lobby' || this.status === 'finished' ? null : '게임 중에는 바꿀 수 없어요.';
}
/** A computer's level and luck; computers saved without one get it from their id. */
/** Admin game speed (docs/14 §5), read live so a change reaches running games too. */
gameSpeed(): number {
return clampGameSpeed(this.deps.settings?.getSite().gameSpeed);
}
profile(bot: string): BotProfile {
return (this.botProfiles[bot] ??= profileFromId(bot));
}
seat(userId: string, seat?: number): string | null {
const err = this.requireLobby();
if (err) return err;
@@ -616,7 +730,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.
@@ -675,8 +789,10 @@ export class Room {
const used = new Set(this.seatedIds().map(botNumber));
let n = 1;
while (used.has(n)) n++;
const id = makeBotId(n, ulid(this.now()));
const id = makeBotId(n, ulid(this.now(), secureRandom));
this.seats[target] = { userId: id, ready: true };
// Any level 1~60 and its own luck, from OS randomness; the host may pick 쉬움/보통/어려움 afterwards.
this.botProfiles[id] = newBotProfile();
if (this.config.visibility === 'public') this.config = { ...this.config, visibility: 'private' };
this.persist({ actorId: userId, kind: 'addBot', data: { seat: target, bot: id } });
this.broadcastRoom();
@@ -691,18 +807,31 @@ export class Room {
if (seat < 0 || !isBotId(botId)) return '없는 컴퓨터예요.';
this.seats[seat] = null;
this.rematchVotes.delete(botId);
delete this.botProfiles[botId];
this.persist({ actorId: userId, kind: 'removeBot', data: { bot: botId } });
this.broadcastRoom();
return null;
}
/** Host picks a computer's difficulty: a new level from that range (랜덤 = any), hidden until the game is over. */
setBotLevel(userId: string, botId: string, pick: BotPick): string | null {
if (userId !== this.hostId) return '방장만 난이도를 바꿀 수 있어요.';
const err = this.requireLobby();
if (err) return err;
if (this.seatOf(botId) < 0 || !isBotId(botId)) return '없는 컴퓨터예요.';
this.botProfiles[botId] = repick(this.profile(botId), pick);
this.persist({ actorId: userId, kind: 'botLevel', data: { bot: botId, pick } });
this.broadcastRoom();
return null;
}
chat(userId: string, text: string): string | null {
if (!this.config.chatEnabled) return '이 방은 채팅을 쓰지 않아요.';
if (!this.isParticipant(userId)) return '방에 들어와야 채팅할 수 있어요.';
if (this.gameChatOnly()) return '게임 중에는 게임 화면의 채팅을 써 주세요.';
// No pace limit: every line goes out as soon as it is typed (the socket's own flood guard still applies).
const now = this.now();
if (now - (this.lastChatAt.get(userId) ?? 0) < 500) return '조금 천천히 보내 주세요.';
this.lastChatAt.set(userId, now);
this.typingAt.delete(userId);
const clean = text.replace(/[\u0000-\u001f\u007f]/g, ' ').trim();
if (!clean) return null;
const msg: Extract<ServerMessage, { t: 'chat' }> = {
@@ -714,6 +843,7 @@ export class Room {
this.chatLog.push(msg);
if (this.chatLog.length > CHAT_HISTORY) this.chatLog.shift();
for (const c of this.conns.values()) c.send(msg);
if (!isBotId(userId)) this.brain.onHumanChat(userId, msg.text);
return null;
}
@@ -722,6 +852,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();
@@ -742,17 +887,18 @@ export class Room {
if (players.length > range.max) return `최대 ${range.max}명까지 할 수 있어요.`;
if (this.hasBots() && !botsAllowed(this.config.gameId)) return '컴퓨터는 이 게임을 할 수 없어요.';
if (players.every(isBotId)) return '사람이 한 명은 앉아야 해요.';
return this.startGame(players);
return this.beginGame(players);
}
rematch(userId: string): string | null {
if (this.status !== 'finished') return '게임이 끝난 뒤에 누를 수 있어요.';
if (this.starting) return '게임을 준비하고 있어요.';
if (this.seatOf(userId) < 0) return '자리에 앉아야 해요.';
this.rematchVotes.add(userId);
const seated = this.seatedIds();
const range = this.playerRange();
if (seated.length >= range.min && seated.every((u) => isBotId(u) || this.rematchVotes.has(u))) {
return this.startGame(this.orderedPlayers());
return this.beginGame(this.orderedPlayers());
}
this.persist(null);
this.broadcastRoom();
@@ -766,7 +912,8 @@ export class Room {
return h > 0 ? [...ids.slice(h), ...ids.slice(0, h)] : ids;
}
private startGame(players: string[]): string | null {
/** The options the game would start with, or why it can't start. */
private startOptions(players: string[]): { options: unknown } | string {
const def = this.def;
const lk = this.locked(def.id);
const parsed = def.optionsSchema.safeParse(lk.paths.length ? applyLocks(this.config.options, lk.defaults, lk.paths) : this.config.options);
@@ -775,22 +922,76 @@ export class Room {
if (countErr) return countErr;
const eff = this.deps.settings?.game(def.id);
if (eff && !eff.enabled) return '관리자가 이 게임을 잠시 막아 두었어요.';
this.config = { ...this.config, options: parsed.data };
const seed = createSeed();
// Data the server decides (e.g. the admin-edited 라이어 word-bank version) goes with the options, so replays match.
return { options: def.prepareOptions ? def.prepareOptions(parsed.data) : parsed.data };
}
/**
* Starts a game. With computers in a game of chance, a few shuffles are tried first for their luck (docs/04 §5.1)
* on the luck worker; the room shows "섞는 중" and starts when they are done (well under a few seconds). If the
* seats changed meanwhile, nothing starts and the host can press start again.
*/
private beginGame(players: string[]): string | null {
const ok = this.startOptions(players);
if (typeof ok === 'string') return ok;
const bots = players.filter(isBotId);
const luckSeed = this.deps.luckSeed;
if (!luckSeed || !luckApplies(this.def.id) || shufflesFor(bots.map((b) => this.profile(b).luck)) <= 1) return this.startGame(players, null);
const job: LuckJob = {
gameId: this.def.id,
players,
options: ok.options,
now: this.now(),
gameNo: this.gameNo + 1,
luck: Object.fromEntries(bots.map((b) => [b, this.profile(b).luck])),
levels: Object.fromEntries(bots.map((b) => [b, this.profile(b).level])),
budgetMs: LUCK_BUDGET_MS,
};
this.starting = true;
this.broadcastRoom();
const gameNo = this.gameNo;
void luckSeed(job)
.catch((err) => {
this.deps.log?.('warn', 'luck shuffle failed', { room: this.code, err: String(err) });
return null;
})
.then((picked) => {
this.starting = false;
if (this.closed) return;
const same = this.gameNo === gameNo && this.requireLobby() === null && this.orderedPlayers().join() === players.join();
const err = same ? this.startGame(players, picked) : null;
if (err) this.notice('start-failed', err);
if (!same || err) this.broadcastRoom();
});
return null;
}
private startGame(players: string[], picked: { seed: ChaChaSeed; tried: number } | null): string | null {
const def = this.def;
const ok = this.startOptions(players);
if (typeof ok === 'string') return ok;
this.config = { ...this.config, options: ok.options };
const seed = picked?.seed ?? createSeed();
const seedHex = seedToHex(seed);
const rng = SeededRng.fromSeed(seed);
const now = this.now();
const gameNo = this.gameNo + 1;
let state: unknown;
try {
state = def.setup({ players, options: parsed.data, rng, now, gameNo });
state = def.setup({ players, options: ok.options, rng, now, gameNo });
} catch (err) {
this.deps.log?.('error', 'setup failed', { room: this.code, err: String(err) });
return '게임을 시작하지 못했어요.';
}
const gamePk = ulid(now);
const seedHash = sha256Hex(seedHex);
this.deps.store.insertGame({ id: gamePk, roomId: this.id, gameNo, gameId: def.id, options: parsed.data, seedHash, startedAt: now });
// From the second game on, each computer's level moves a little around where it started (docs/09 §9.1).
const bots: Record<string, { level: number; luck: number }> = {};
for (const b of players.filter(isBotId)) {
const p = (this.botProfiles[b] = drift(this.profile(b)));
bots[b] = { level: p.level, luck: p.luck };
}
this.deps.store.insertGame({ id: gamePk, roomId: this.id, gameNo, gameId: def.id, options: ok.options, seedHash, startedAt: now });
this.gameNo = gameNo;
this.game = {
gameId: def.id,
@@ -804,6 +1005,7 @@ export class Room {
players,
finished: false,
deadlineFloor: null,
...(Object.keys(bots).length ? { bots, shuffles: picked?.tried ?? 1 } : {}),
};
this.status = 'playing';
this.rematchVotes.clear();
@@ -814,6 +1016,7 @@ export class Room {
this.broadcastRoom();
this.broadcastState([{ type: 'gameStarted' }]);
this.scheduleTimer();
this.brain.onGameStart();
return null;
}
@@ -870,6 +1073,7 @@ export class Room {
} else {
this.persist({ actorId: userId, kind: system ? 'auto' : 'act', data: action, at: now });
this.broadcastState(next.events, userId, cs);
this.brain.onAction(userId, action);
}
const result = def.result(g.state);
if (result) this.finishGame(result);
@@ -935,13 +1139,68 @@ export class Room {
this.persist({ actorId: null, kind: 'finish', data: { result, voided } });
this.broadcastState([{ type: 'gameOver' }]);
for (const c of this.conns.values()) c.send({ t: 'result', seq: this.seq, result });
if (this.botActivity.size) this.botActivity.clear();
this.broadcastRoom();
if (!voided) this.brain.onGameEnd(result.ranking);
}
// ---------------------------------------------------------------- timers
/** The deadline clients see (`def.publicDeadline`, default the effective one); timers use `effectiveDeadline`. */
private publicDeadline(): number | null {
const d = this.effectiveDeadline(true);
const g = this.game;
return g && this.def.publicDeadline ? this.def.publicDeadline(g.state, d) : d;
}
/**
* How much later than the game's own deadline `u`'s clock runs out: the time their screen took to finish animating
* the last change. Until their screen says so, the timer waits up to `REVEAL_MAX_MS` (scaled like the animations);
* computers and screens that never report get no extra time;
* `provisional` (the deadline shown to clients) counts only the time that has passed so far.
*/
private revealExtra(u: string, provisional = false): number {
const r = this.reveal;
if (!r || !this.game || this.def.realtime || !this.settles.has(u)) return 0;
const cap = Math.round((REVEAL_MAX_MS * BOT_SLOWDOWN) / this.gameSpeed());
const done = r.done.get(u);
if (done !== undefined) return Math.min(cap, done - r.at);
return provisional ? Math.min(cap, Math.max(0, this.now() - r.at)) : cap;
}
/**
* What a step is: its clock. Players answering one by one inside a shared clock (votes) or a chat line keep the
* time already given; a new clock (next turn, next phase) is a new step.
*/
private revealKey(): string {
return JSON.stringify(this.def.deadline?.(this.game!.state) ?? null);
}
/**
* Extra time on `u`'s clock: the slowest screen among the players who still have to answer (and `u`). A shared
* clock (a vote, a stand-in the room times for everybody) thus never cuts short someone whose screen is still
* animating because another screen was faster.
*/
private clockExtra(u: string, provisional = false): number {
const answer = this.def.activePlayers(this.game!.state);
return Math.max(this.revealExtra(u, provisional), ...answer.map((p) => this.revealExtra(p, provisional)));
}
/** A player's screen finished animating the state `seq` (or a later one): their clock starts now. */
settled(userId: string, seq: number): void {
const r = this.reveal;
if (!r || seq < r.seq || r.done.has(userId) || !this.game || this.game.finished || !this.game.players.includes(userId)) return;
this.settles.add(userId);
r.done.set(userId, this.now());
this.scheduleTimer();
const after = this.publicDeadline();
if (after === this.sentDeadline) return;
this.sentDeadline = after;
for (const c of this.conns.values()) c.send({ t: 'deadline', deadline: after });
}
/** Earliest time any timed player must be auto-acted for. */
effectiveDeadline(): number | null {
effectiveDeadline(provisional = false): number | null {
const g = this.game;
if (!g || g.finished || this.status !== 'playing') return null;
const def = this.def;
@@ -951,7 +1210,7 @@ export class Room {
const graceMs = def.disconnectGraceMs?.(g.state) ?? this.config.graceSec * 1000;
let best: number | null = null;
for (const u of timed) {
let d = base;
let d = base === null ? null : base + this.clockExtra(u, provisional);
const p = this.presence.get(u);
if (p && !p.connected) {
const grace = p.since + graceMs;
@@ -995,7 +1254,7 @@ export class Room {
const timed = def.timeoutPlayers ? def.timeoutPlayers(g.state) : def.activePlayers(g.state);
const graceMs = def.disconnectGraceMs?.(g.state) ?? this.config.graceSec * 1000;
for (const u of timed) {
let d = base;
let d = base === null ? null : base + this.clockExtra(u);
const p = this.presence.get(u);
if (p && !p.connected) {
const grace = p.since + graceMs;
@@ -1031,6 +1290,7 @@ export class Room {
/** Ends a running game uncounted and sends everyone still in the room away (the manager then closes it). */
closeWith(summary: string, notice: string): void {
this.closed = true;
if (this.game && !this.game.finished) {
this.finishGame({ ranking: [this.game.players], summary, reason: 'abandoned' }, true);
}
@@ -1044,6 +1304,7 @@ export class Room {
}
shutdown(): void {
this.closed = true;
this.flushStream();
this.clearTimer();
for (const c of this.conns.values()) {

View File

@@ -0,0 +1,142 @@
/**
* 루미큐브 through a real Room (docs/games/rummikub.md §5.6, §8.2–§8.3): the working table is broadcast to everybody
* on every drop, the drag preview goes out as a public `stream` message, and a v1 save is migrated on restore.
*/
import { describe, expect, test } from 'bun:test';
import type { ServerMessage } from '@bg/shared';
import { GAMES } from '@bg/games';
import { cellsOf, freeSpot, type RummikubState, type RummikubView } from '@bg/games/rummikub';
import { openDb } from '../db';
import { TokenBucket } from '../ws/rate-limit';
import { Room, type Conn, type RoomConfig, type RoomSnapshot } from './room';
import { RoomStore } from './store';
type Msgs = ServerMessage[];
type StateMsg = Extract<ServerMessage, { t: 'state' }>;
function harness() {
const db = openDb(':memory:');
const store = new RoomStore(db);
let now = 1_000_000;
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
const games = { rummikub: GAMES.rummikub! };
const deps = { store, games, users: { publicUser: (id: string) => ({ id, nickname: id, avatar: null, kind: 'guest' as const }) }, now: clock.now };
const config: RoomConfig = {
gameId: 'rummikub',
options: { ...games.rummikub.defaultOptions },
maxPlayers: 2,
visibility: 'private',
allowSpectators: true,
chatEnabled: true,
chatFilter: true,
graceSec: 60,
};
const room = new Room('room1', '482913', config, 'A', deps);
store.insertRoom({ id: 'room1', code: '482913', hostId: 'A', gameId: 'rummikub', status: 'lobby', visibility: 'private', config, stateJson: '{}', now });
const conn = (p: string) => {
const msgs: Msgs = [];
const c: Conn & { msgs: Msgs } = { userId: p, msgs, send: (m) => msgs.push(m), close: () => {} };
return c;
};
const conns: Record<string, Conn & { msgs: Msgs }> = { A: conn('A'), B: conn('B') };
room.join(conns.A!, 'player');
room.join(conns.B!, 'player');
expect(room.start('A')).toBeNull();
room.clearTimer();
conns.S = conn('S');
room.join(conns.S, 'spectator');
const state = () => room.game!.state as RummikubState;
let cs = 100;
const act = (p: string, a: unknown) => {
room.act(p, ++cs, a);
room.clearTimer();
return cs;
};
return { room, store, deps, clock, conns, state, act };
}
const lastView = (m: Msgs) => (m.filter((x): x is StateMsg => x.t === 'state').at(-1)!.view as RummikubView);
describe('루미큐브 room flow', () => {
test('놓을 때마다 바닥이 모두(상대·관전자)에게 바로 보이고, 받침대의 나머지 타일은 보이지 않음', () => {
const { conns, state, act } = harness();
const cur = state().current;
const other = cur === 'A' ? 'B' : 'A';
const [t1, t2, ...rest] = state().racks[cur]! as [string, string, ...string[]];
act(cur, { type: 'arrange', cells: [{ id: t1, r: 1, c: 2 }], turn: state().turnNo });
for (const who of [other, 'S']) {
const v = lastView(conns[who]!.msgs);
expect(v.draft!.cells).toEqual([{ id: t1, r: 1, c: 2 }]);
expect(v.draftEdits).toBe(1);
const json = JSON.stringify(v);
for (const id of [t2, ...rest]) expect(json.includes(`"${id}"`)).toBe(false);
}
// Moving it again: everybody sees the new place.
act(cur, { type: 'arrange', cells: [{ id: t1, r: 3, c: 7 }, { id: t2, r: 3, c: 8 }], turn: state().turnNo });
expect(lastView(conns[other]!.msgs).draft!.cells).toEqual([
{ id: t1, r: 3, c: 7 },
{ id: t2, r: 3, c: 8 },
]);
// 되돌리기: back to the turn start for everybody.
act(cur, { type: 'resetDraft' });
expect(lastView(conns.S!.msgs).draft!.cells).toEqual([]);
});
test('끄는 중인 타일은 stream 메시지로만 중계되고(전체 view 재전송 없음), 받침대 타일은 뒷면(null)', () => {
const { conns, state, act } = harness();
const cur = state().current;
const other = cur === 'A' ? 'B' : 'A';
const [t1, t2] = state().racks[cur]! as [string, string];
act(cur, { type: 'arrange', cells: [{ id: t1, r: 0, c: 0 }], turn: state().turnNo });
const before = { o: conns[other]!.msgs.length, s: conns.S!.msgs.length, me: conns[cur]!.msgs.length };
const mine = act(cur, { type: 'drag', ids: [t1, t2], x: 4.5, y: 2, turn: state().turnNo });
for (const [who, n] of [
[other, before.o],
['S', before.s],
] as const) {
const got = conns[who]!.msgs.slice(n);
expect(got).toEqual([{ t: 'stream', seq: expect.any(Number), events: [{ type: 'drag', player: cur, turn: state().turnNo, tiles: [t1, null], x: 4.5, y: 2 }] }]);
}
// The sender gets the same stream message with its cs (no `pending` lock, no reject).
expect(conns[cur]!.msgs.slice(before.me)).toEqual([{ t: 'stream', seq: expect.any(Number), events: expect.any(Array), cs: mine }]);
// A late drag from the other player is dropped silently: no error, nothing relayed.
const n = conns[other]!.msgs.length;
act(other, { type: 'drag', ids: [], x: 0, y: 0 });
expect(conns[other]!.msgs.slice(n).some((m) => m.t === 'reject')).toBe(false);
});
test('drag preview pace (5/s) + drops stay well under the socket token bucket (20/s, burst 40)', () => {
const bucket = new TokenBucket(20, 40, 0);
let dropped = 0;
// 30 seconds of non-stop dragging: a preview every 200 ms and a drop every second.
for (let t = 0; t < 30_000; t += 200) {
if (!bucket.take(t)) dropped++;
if (t % 1000 === 0 && !bucket.take(t)) dropped++;
}
expect(dropped).toBe(0);
});
test('예전 저장(v1, 칸 위치 없음)을 불러오면 칸 판으로 바뀌고 이어서 둘 수 있음', () => {
const { room, store, deps, state, act } = harness();
act(state().current, { type: 'draw' });
room.clearTimer();
const { seq, stateJson } = store.openRooms()[0]!;
const snap = JSON.parse(stateJson) as RoomSnapshot;
const g = snap.game!.state as Record<string, any>;
// What a v1 save looked like: sets without places, a draft of sets with an undo history.
g.table = [];
g.draft = { sets: [], history: [], edits: 0 };
snap.game!.stateVersion = 1;
const restored = Room.restore('room1', '482913', seq, snap, deps);
restored.clearTimer();
const s = restored.game!.state as RummikubState;
expect(restored.game!.stateVersion).toBe(2);
expect(s.draft).toEqual({ cells: [], edits: 0 });
const p = s.current;
const id = s.racks[p]![0]!;
const spot = freeSpot(cellsOf(s.table), 1)!;
restored.act(p, 1, { type: 'arrange', cells: [{ id, ...spot }] });
restored.clearTimer();
expect((restored.game!.state as RummikubState).draft.cells).toEqual([{ id, ...spot }]);
});
});

View File

@@ -0,0 +1,115 @@
/** 사천성 through a real Room: a practice race against a computer to the end, away players (docs/games/shisen.md §8). */
import { afterEach, describe, expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import { findPair, type ShisenState, type ShisenView } from '@bg/games/shisen';
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 ShisenView;
function twoPlayers(timeLimitSec: number | null) {
const h = harness();
const r = h.manager.create('A', 'shisen', '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: { size: 'small', hints: true, timeLimitSec } })).toBeNull();
expect(room.start('A')).toBeNull();
h.clock.advance(3000);
room.onTimer();
return { h, room, a, b, s: () => room.game!.state as ShisenState };
}
describe('사천성 room flow', () => {
test('컴퓨터와 연습: 사람은 2초마다 한 쌍씩 없애다 1분 뒤 포기하고, 컴퓨터는 자기 판을 끝까지 풀어요', () => {
const h = harness();
const room = h.manager.createPractice('A', 'shisen') 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 removed = 0;
const s = () => room.game!.state as ShisenState;
for (let i = 0; i < 4 * 1000 && !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 v = lastView(a);
if (i % 8 === 0 && v.phase === 'playing' && v.board && v.seats.find((x) => x.id === 'A')!.status === 'playing') {
if (h.clock.now() - v.countdownEndsAt > 60_000) room.act('A', ++cs, { type: 'stop' });
else {
const p = findPair(v.board.cells, v.board.rows, v.board.cols);
if (p) {
room.act('A', ++cs, { type: 'pair', a: p[0], b: p[1] });
removed++;
}
}
}
}
expect(room.game!.finished).toBe(true);
expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0);
expect(s().boards.A!.removed).toBe(removed);
expect(removed).toBeGreaterThan(20);
expect(s().status[bot]).toBe('solved');
expect(lastView(a).result!.ranking.map((r) => r.id)).toEqual([bot, 'A']);
});
test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => {
const { h, room, b, s } = twoPlayers(300);
expect(s().phase).toBe('playing');
room.disconnect(b);
expect(room.effectiveDeadline()).toBe(s().endsAt);
h.clock.advance(70_000);
room.onTimer();
expect(s().status.B).toBe('playing');
h.clock.advance(s().endsAt! - h.clock.now());
room.onTimer();
expect(room.game!.finished).toBe(true);
expect(s().final!.endReason).toBe('time');
});
test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => {
const { h, room, b, s } = twoPlayers(null);
expect(room.effectiveDeadline()).toBeNull();
room.disconnect(b);
const d = room.effectiveDeadline()!;
h.clock.advance(d - h.clock.now());
room.onTimer();
expect(s().status.B).toBe('done');
expect(room.effectiveDeadline()).toBeNull();
room.act('A', 1, { type: 'stop' });
expect(room.game!.finished).toBe(true);
expect(s().final!.ranking.map((r) => r.status)).toEqual(['done', 'done']);
});
});

View File

@@ -0,0 +1,129 @@
/**
* 젝스님트 through a real Room (docs/games/six-nimmt.md §10): practice games against computers played to the end from
* the person's own screen, with the simultaneous secret pick, the row choice, the pro draft and timeouts on the clock.
*/
import { afterEach, describe, expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import type { SixNimmtAction, SixNimmtState, SixNimmtView } from '@bg/games/six-nimmt';
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 SixNimmtView);
/** What the person presses, read only from their own screen (the safest-looking card, or the fewest-bulls row). */
function personMove(v: SixNimmtView, me: string, n: number): SixNimmtAction | null {
if (v.phase === 'draft') return v.draft!.at === me ? { type: 'DRAFT', card: v.draft!.pool[n % v.draft!.pool.length]! } : null;
if (v.phase === 'select') {
if (v.players[me]!.picked || !v.my) return null;
const hand = [...v.my.hand].sort((a, b) => (a.preview?.takes ?? 0) - (b.preview?.takes ?? 0));
return { type: 'SELECT', card: hand[n % 2 === 0 ? 0 : hand.length - 1]!.n };
}
const pd = v.pending;
if (v.phase !== 'choose' || !pd || pd.player !== me) return null;
if (pd.kind === 'place') return { type: 'PLACE', row: pd.choices[0]!.row, side: pd.choices[0]!.side };
const best = v.rows.reduce((b, r, i) => (r.bulls < v.rows[b]!.bulls ? i : b), 0);
return { type: 'TAKE_ROW', row: best };
}
describe('젝스님트 room flow', () => {
test.each([
[1, {}],
[3, { deck: 'pro', endMode: 'rounds', rounds: 2 }],
[4, { placement: 'both', lowCard: 'choose', endMode: 'rounds', rounds: 2 }],
] as const)('컴퓨터 %i명과 연습 %j: 사람은 자기 화면만 보고 끝까지, 컴퓨터가 고른 카드는 공개 전까지 안 보여요', (nBots, options) => {
const h = harness();
let room: Room;
if (nBots === 1) room = h.manager.createPractice('A', 'six-nimmt') as Room;
else {
const r = h.manager.create('A', 'six-nimmt', 'private');
if (typeof r === 'string') throw new Error(r);
room = r;
expect(room.configure('A', { options: { ...GAMES['six-nimmt']!.defaultOptions, ...options } })).toBeNull();
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;
let chose = 0;
for (let i = 0; i < 60_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);
for (const v of vs.slice(seen)) {
// A computer's secret pick never reaches my screen before the reveal.
for (const b of bots) expect(JSON.stringify(v)).not.toContain(`six-sel:${b}`);
expect(v.me).toBe('A');
}
seen = vs.length;
const v = vs.at(-1);
const m = v && personMove(v, 'A', mine);
if (m) {
if (m.type === 'TAKE_ROW' || m.type === 'PLACE') chose++;
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 SixNimmtState;
expect(s.timeouts.A).toBe(0); // every step of the person was a real press
const last = views(a).at(-1)!;
expect(last.result!.ranking.map((r) => r.player).sort()).toEqual(['A', ...bots].sort());
expect(last.result!.ranking[0]!.total).toBe(Math.min(...s.seats.map((p) => s.totals[p]!)));
expect(mine).toBeGreaterThanOrEqual(10);
if (nBots === 1) expect(chose + mine).toBeGreaterThan(10);
const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!;
expect(JSON.parse(row.result_json).practice).toBe(true);
});
test('시간 초과: 사람이 아무것도 안 하면 제한 시간마다 자동으로 내고 3번이면 자리 비움', () => {
const h = harness();
const room = h.manager.createPractice('A', 'six-nimmt') as Room;
rooms.push(room);
const a = h.conn('A');
room.join(a, 'player');
expect(room.start('A')).toBeNull();
for (let i = 0; i < 2000; i++) {
h.clock.advance(500);
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();
if ((room.game!.state as SixNimmtState).timeouts.A! >= 3) break;
}
const s = room.game!.state as SixNimmtState;
expect(s.timeouts.A).toBeGreaterThanOrEqual(3);
expect(views(a).at(-1)!.players.A!.away).toBe(true);
});
});

View File

@@ -0,0 +1,121 @@
/** 솔리테어 through a real Room: a practice race against a computer, hidden cards never reach my screen, away players (docs/games/solitaire.md §8). */
import { afterEach, describe, expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import { legalOn, type SolitaireState, type SolitaireView } from '@bg/games/solitaire';
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 SolitaireView;
function twoPlayers(h: ReturnType<typeof harness>, options: Record<string, unknown>) {
const r = h.manager.create('A', 'solitaire', '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 })).toBeNull();
expect(room.start('A')).toBeNull();
h.clock.advance(3000);
room.onTimer();
return { room, a, b, s: () => room.game!.state as SolitaireState };
}
describe('solitaire · 솔리테어 room flow', () => {
test('컴퓨터와 연습: 사람은 2초마다 한 수, 1분 뒤 포기하고 컴퓨터는 끝까지 가요. 내 화면에는 뒤집힌 카드와 더미가 없어요', () => {
const h = harness();
const room = h.manager.createPractice('A', 'solitaire') 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 moves = 0;
const s = () => room.game!.state as SolitaireState;
for (let i = 0; i < 4 * 1000 && !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 v = lastView(a);
const playing = v.board && v.phase === 'playing' && v.seats.find((x) => x.id === 'A')!.status === 'playing';
if (playing) {
const b = s().boards.A!;
const json = JSON.stringify(v);
for (const c of [...b.stock, ...b.t.flatMap((col, k) => col.slice(0, b.down[k]))]) expect(json).not.toContain(`"${c}"`);
}
if (i % 8 === 0 && playing) {
if (h.clock.now() - v.countdownEndsAt > 60_000) room.act('A', ++cs, { type: 'stop' });
else {
const legal = legalOn(v.board!).filter((m) => m.type !== 'undo' && m.type !== 'auto');
const m = legal.find((x) => x.type === 'move' && x.to === 'f') ?? legal.find((x) => x.type === 'draw') ?? legal[0];
if (m) {
room.act('A', ++cs, m);
moves++;
}
}
}
}
expect(room.game!.finished).toBe(true);
expect(moves).toBeGreaterThan(10);
expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0);
expect(s().boards[bot]!.hist.length).toBeGreaterThan(0);
expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort());
});
test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => {
const h = harness();
const { room, b, s } = twoPlayers(h, { mode: 'spider', draw: 1, suits: 2, timeLimitSec: 600 });
expect(s().phase).toBe('playing');
room.disconnect(b);
expect(room.effectiveDeadline()).toBe(s().endsAt);
h.clock.advance(70_000);
room.onTimer();
expect(s().status.B).toBe('playing');
h.clock.advance(s().endsAt! - h.clock.now());
room.onTimer();
expect(room.game!.finished).toBe(true);
expect(s().final!.endReason).toBe('time');
});
test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => {
const h = harness();
const { room, b, s } = twoPlayers(h, { mode: 'freecell', draw: 1, suits: 1, timeLimitSec: null });
expect(room.effectiveDeadline()).toBeNull();
room.disconnect(b);
const d = room.effectiveDeadline()!;
h.clock.advance(d - h.clock.now());
room.onTimer();
expect(s().status.B).toBe('done');
expect(room.effectiveDeadline()).toBeNull();
room.act('A', 1, { type: 'stop' });
expect(room.game!.finished).toBe(true);
});
});

View File

@@ -0,0 +1,126 @@
/** 스도쿠 through a real Room: a practice race against a computer, the solution never reaches my screen, away players (docs/games/sudoku.md §8). */
import { afterEach, describe, expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import type { SudokuState, SudokuView } from '@bg/games/sudoku';
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 SudokuView;
describe('sudoku room flow', () => {
test('컴퓨터와 연습: 사람은 맞는 숫자를 하나씩 넣고, 컴퓨터도 자기 판을 풀어 끝까지 가요. 다 풀기 전 내 화면에는 정답이 없어요', () => {
const h = harness();
const room = h.manager.createPractice('A', 'sudoku') 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;
const s = () => room.game!.state as SudokuState;
for (let i = 0; i < 4 * 1900 && !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 v = lastView(a);
const playing = v.board && v.phase === 'playing' && v.seats.find((x) => x.id === 'A')!.status === 'playing';
if (playing) {
expect(v.board!.solution).toBeUndefined();
expect(JSON.stringify(v)).not.toContain(s().puzzle.solution);
}
// The person fills the first empty cell with the right number every 2 s.
if (i % 8 === 0 && playing) {
const k = v.board!.values.indexOf('0');
if (k >= 0) room.act('A', ++cs, { type: 'set', i: k, n: Number(s().puzzle.solution[k]) });
}
}
expect(room.game!.finished).toBe(true);
expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0);
expect(s().status.A).toBe('solved');
expect(s().status[bot]).toBe('solved');
expect(lastView(a).board!.solution).toBe(s().puzzle.solution);
expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort());
});
test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => {
const h = harness();
const r = h.manager.create('A', 'sudoku', '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: { difficulty: 'easy', hints: true, timeLimitSec: 600 } })).toBeNull();
expect(room.start('A')).toBeNull();
h.clock.advance(3000);
room.onTimer();
const s = () => room.game!.state as SudokuState;
expect(s().phase).toBe('playing');
room.disconnect(b);
expect(room.effectiveDeadline()).toBe(s().endsAt);
h.clock.advance(70_000);
room.onTimer();
expect(s().status.B).toBe('playing');
h.clock.advance(s().endsAt! - h.clock.now());
room.onTimer();
expect(room.game!.finished).toBe(true);
expect(s().final!.endReason).toBe('time');
});
test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => {
const h = harness();
const r = h.manager.create('A', 'sudoku', '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: { difficulty: 'normal', hints: false, timeLimitSec: null } })).toBeNull();
expect(room.start('A')).toBeNull();
h.clock.advance(3000);
room.onTimer();
const s = () => room.game!.state as SudokuState;
expect(room.effectiveDeadline()).toBeNull();
room.disconnect(b);
const d = room.effectiveDeadline()!;
h.clock.advance(d - h.clock.now());
room.onTimer();
expect(s().status.B).toBe('done');
expect(room.effectiveDeadline()).toBeNull();
h.clock.advance(60_000);
room.onTimer();
expect(s().status.A).toBe('playing');
room.act('A', 1, { type: 'stop' });
expect(room.game!.finished).toBe(true);
});
});

View File

@@ -0,0 +1,159 @@
/** 타자 대결 through a real Room: progress streams, a practice game against a computer, away players (docs/games/typing.md §8). */
import { afterEach, describe, expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import type { TypingState, TypingView } from '@bg/games/typing';
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 TypingView;
function twoPlayers(options: Record<string, unknown>) {
const h = harness();
const r = h.manager.create('A', 'typing', '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: { ...GAMES.typing!.defaultOptions, ...options } })).toBeNull();
expect(room.start('A')).toBeNull();
h.clock.advance(3000);
room.onTimer();
return { h, room, a, b, s: () => room.game!.state as TypingState };
}
describe('타자 대결 room flow', () => {
test('연습: 먼저 다 친 사람이 방을 나가도 남은 사람은 끝까지 쳐요', () => {
const { h, room, b, s } = twoPlayers({ mode: 'practice', category: 'word' });
const typeAll = (who: string) => {
const n = s().items.length;
for (let i = 0; i < n; i++) {
h.clock.advance(3000);
room.act(who, 100 + i, { type: 'submit', item: i, text: s().items[i]! });
}
};
typeAll('A');
expect(s().rs.A!.finishedAt).not.toBeNull();
room.leave('A');
expect(s().phase).toBe('playing');
expect(lastView(b).upcoming[0]!.idx).toBe(0);
typeAll('B');
expect(b.msgs.filter((m) => m.t === 'reject')).toEqual([]);
expect(s().phase).toBe('ended');
expect(s().final!.ranking[0]).toMatchObject({ id: 'B', left: false });
});
test('진행은 stream으로만 가고(보기 다시 계산 없음), 먼저 정확하게 친 사람이 점수를 얻어요', () => {
const { h, room, a, b, s } = twoPlayers({ rounds: 1 });
const v = lastView(b);
expect(v.phase).toBe('playing');
const item = v.upcoming[0]!;
// A paste the moment the text appears is refused.
room.act('B', 1, { type: 'submit', item: item.idx, text: item.text });
expect((b.msgs.filter((m) => m.t === 'reject').at(-1) as { reason: string }).reason).toContain('너무 빨라요');
const states = b.msgs.filter((m) => m.t === 'state').length;
h.clock.advance(1500);
room.act('A', 1, { type: 'progress', item: item.idx, text: item.text.slice(0, 2) });
const stream = b.msgs.filter((m) => m.t === 'stream').at(-1) as Extract<ServerMessage, { t: 'stream' }>;
expect(stream.events).toEqual([expect.objectContaining({ type: 'progress', player: 'A', item: item.idx })]);
expect(b.msgs.filter((m) => m.t === 'state').length).toBe(states);
h.clock.advance(3000);
room.act('A', 2, { type: 'submit', item: item.idx, text: item.text });
expect(a.msgs.filter((m) => m.t === 'reject').map((m) => JSON.stringify(m))).toEqual([]);
expect(s().totals.A!.points).toBe(1);
expect(lastView(b).last).toMatchObject({ winner: 'A', text: item.text });
// The next item opens after the gap, from the server clock.
expect(lastView(b).upcoming).toEqual([]);
h.clock.advance(1500);
room.onTimer();
expect(lastView(b).upcoming[0]!.idx).toBe(1);
});
test('컴퓨터와 연습(타수 비교): 사람도 컴퓨터도 끝까지 치고, 거절 없이 끝나요', () => {
const h = harness();
const room = h.manager.createPractice('A', 'typing') as Room;
rooms.push(room);
const a = h.conn('A');
room.join(a, 'player');
expect(room.configure('A', { options: { ...GAMES.typing!.defaultOptions, mode: 'speed', rounds: 1 } })).toBeNull();
expect(room.start('A')).toBeNull();
const bot = room.game!.players.find(isBotId)!;
expect(bot).toBeDefined();
let cs = 0;
for (let i = 0; i < 4 * 400 && !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 sends a line every 6 seconds, read from their own screen.
const v = lastView(a);
const me = v.seats.find((x) => x.id === 'A')!;
if (i % 24 === 23 && v.phase === 'playing' && !me.finished && v.upcoming[0]) room.act('A', ++cs, { type: 'submit', item: v.upcoming[0].idx, text: v.upcoming[0].text });
}
expect(room.game!.finished).toBe(true);
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
const s = room.game!.state as TypingState;
expect(s.totals.A!.keys).toBeGreaterThan(0);
expect(s.totals[bot]!.keys).toBeGreaterThan(0);
expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort());
});
test('서바이벌 문장별(무제한은 자동 시간으로): 끊긴 사람을 기다리지 않고, 먼저 친 사람이 남아 이겨요', () => {
const { h, room, a, b, s } = twoPlayers({ mode: 'survival', elimination: 'sentence', timeLimit: null, rounds: 1 });
// 서바이벌 always has a clock (무제한 plays as 자동).
expect(s().curEndsAt).not.toBeNull();
room.disconnect(b);
const item = lastView(a).upcoming[0]!;
h.clock.advance(4000);
room.act('A', 1, { type: 'submit', item: item.idx, text: item.text });
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
expect(room.game!.finished).toBe(true);
expect(s().rs.B!.outReason).toBe('slowest');
expect(lastView(a).result!.ranking[0]!.id).toBe('A');
});
test('타수 비교 무제한: 끊긴 사람은 유예 뒤 친 데까지로 멈추고, 다음 타이머는 없어요', () => {
const { h, room, a, b, s } = twoPlayers({ mode: 'speed', timeLimit: null, rounds: 1 });
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().rs.B!.finishedAt).not.toBeNull();
expect(room.effectiveDeadline()).toBeNull();
let cs = 0;
while (!room.game!.finished) {
const v = lastView(a);
h.clock.advance(5000);
room.act('A', ++cs, { type: 'submit', item: v.upcoming[0]!.idx, text: v.upcoming[0]!.text });
}
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
expect(lastView(a).result!.ranking[0]!.id).toBe('A');
});
});

View 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);
});

View File

@@ -216,6 +216,45 @@ describe('M1 integration scenarios', () => {
expect(h.res.status).toBe(200);
});
test('10b. chat has its own budget: a fast run of lines (with 입력 중 signals) all arrives and leaves game moves untouched', async () => {
const s = start();
const a = await client(s, '빠른손');
const code = await createRoom(s, a);
await join(a, code);
for (let i = 0; i < 60; i++) {
a.send({ t: 'typing', on: true, ch: 'room' });
a.send({ t: 'chat', text: `줄 ${i}` });
a.send({ t: 'typing', on: false, ch: 'room' });
}
await a.next('chat', (m) => m.text === '줄 59');
expect(a.messages.filter((m) => m.t === 'chat').map((m) => (m as { text: string }).text)).toEqual(Array.from({ length: 60 }, (_, i) => `줄 ${i}`));
// The general budget is still full: a burst of 30 pings all answered.
for (let i = 0; i < 30; i++) a.send({ t: 'ping', ts: i });
await sleep(200);
expect(a.messages.filter((m) => m.t === 'pong').length).toBe(30);
});
test('10c. admin 채팅 도배 방지 (default off) applies at once to open sockets', async () => {
const s = start();
expect(s.settings.getSite().chatFloodGuard).toBe(false);
const a = await client(s, '매크로');
const code = await createRoom(s, a);
await join(a, code);
const lines = () => a.messages.filter((m) => m.t === 'chat').length;
// On: 230 lines at once → only the chat budget (200) gets through.
s.settings.setSite({ ...s.settings.getSite(), chatFloodGuard: true }, 'test');
for (let i = 0; i < 230; i++) a.send({ t: 'chat', text: `켜짐 ${i}` });
await a.next('chat', (m) => m.text === '켜짐 199');
await sleep(200);
expect(lines()).toBe(200);
// Off again: no limit at all.
s.settings.setSite({ ...s.settings.getSite(), chatFloodGuard: false }, 'test');
for (let i = 0; i < 300; i++) a.send({ t: 'chat', text: `꺼짐 ${i}` });
await a.next('chat', (m) => m.text === '꺼짐 299');
expect(lines()).toBe(500);
expect(a.closed).toBeFalsy();
});
test('11. malformed / oversized / schema-invalid messages', async () => {
const s = start();
const a = await client(s, '이상한값');

View File

@@ -1,21 +1,24 @@
/** Wires DB, auth, rooms, HTTP and WebSocket into one Bun server (docs/02 §2). */
import { existsSync } from 'node:fs';
import { existsSync, readFileSync } from 'node:fs';
import { join, normalize } from 'node:path';
import type { Server } from 'bun';
import { GAMES } from '@bg/games';
import { botProfile } from '@bg/shared';
import { Llm } from './ai/llm';
import type { Config } from './config';
import { openDb } from './db';
import { SESSION_COOKIE, Sessions } from './auth/sessions';
import { Users, toPublicUser } from './auth/users';
import { createHttpApp, type HttpDeps } from './http/app';
import { RoomManager } from './rooms/manager';
import { createLuckSeeder } from './rooms/luck';
import type { BotDelayInput } from './rooms/bots';
import { RoomStore } from './rooms/store';
import { Replays } from './rooms/replay';
import { Gateway, type WsData } from './ws/gateway';
import { Audit, Roles } from './admin/roles';
import { SettingsStore } from './admin/settings';
import { LiarBankStore } from './admin/liar-bank';
/** A guest who closed the site and stayed away this long is deleted. */
export const GUEST_IDLE_MS = 24 * 3600_000;
@@ -37,6 +40,8 @@ export interface StartOptions {
botDelay?: (input: BotDelayInput) => number;
/** Upper bound for waiting on Bun's server.stop() (tests shorten it). */
stopWaitMs?: number;
/** Computers' luck on a worker thread (docs/04 §5.1); default on. */
luck?: boolean;
}
export function startServer(opts: StartOptions) {
@@ -53,13 +58,36 @@ export function startServer(opts: StartOptions) {
return u ? toPublicUser(u) : null;
};
const settings = new SettingsStore(db, GAMES);
// 라이어 게임 words the admins changed: loaded before rooms are restored (their games may use an edited bank).
const liarBank = new LiarBankStore(db);
const roles = new Roles(db, config.superadminDiscordIds);
const audit = new Audit(db);
const startedAt = Date.now();
const rooms = new RoomManager({ store, games: GAMES, users: { publicUser }, log, settings, botDelay: opts.botDelay, offlineSince: (id): number | null => gateway.offlineSince(id) });
// Computers talk and play like people with a local model on the GPU when AI_URL is set (docs/06 §12.1, docs/11 §8).
const ai = config.ai ? new Llm({ url: config.ai.url, model: config.ai.model, log }) : null;
if (ai) void ai.warm().then((ok) => log('info', 'ai model', { model: config.ai!.model, ready: ok }));
const luck = opts.luck === false ? null : createLuckSeeder({ log });
const rooms = new RoomManager({
store,
games: GAMES,
users: { publicUser },
log,
settings,
botDelay: opts.botDelay,
ai,
luckSeed: luck ? (job) => luck.seed(job) : undefined,
offlineSince: (id): number | null => gateway.offlineSince(id),
});
const restored = rooms.restoreAll();
log('info', 'rooms restored', restored);
const gateway = new Gateway({ rooms, me: publicUser, log, onClose: (id) => users.touch(id) });
const gateway = new Gateway({
rooms,
me: publicUser,
log,
onClose: (id) => users.touch(id),
build: () => build,
chatFloodGuard: () => settings.getSite().chatFloodGuard,
});
const removeGuest = (id: string) => {
rooms.leaveAll(id);
gateway.closeUser(id);
@@ -81,21 +109,32 @@ export function startServer(opts: StartOptions) {
server?.requestIP(req)?.address ||
'unknown';
const staticDir = opts.staticDir === undefined ? join(import.meta.dir, '../../web/dist') : opts.staticDir;
const serveStatic = staticDir && existsSync(staticDir);
// The web build being served (docs/07 §11.1): pages that were opened with an older one offer to refresh.
const build = serveStatic ? webBuildId(staticDir!) : null;
const app = createHttpApp({
config,
build,
users,
sessions,
rooms,
replays: new Replays(db, GAMES, { publicUser }),
ipOf,
discordExchange: opts.discordExchange,
health: () => ({ ok: ready, rooms: rooms.all().length, connections: gateway.connectionCount }),
health: () => ({
ok: ready,
rooms: rooms.all().length,
connections: gateway.connectionCount,
...(ai ? { ai: { model: ai.stats.model, available: ai.available(), ok: ai.stats.ok, failed: ai.stats.failed, avgMs: ai.stats.avgMs } } : {}),
}),
roles,
settings,
removeGuest,
admin: {
audit,
games: GAMES,
liarBank,
disconnectUser: (id) => gateway.disconnectUser(id),
guestDeleteAt: (u) => (u.kind !== 'guest' || guestKept(u.id) ? null : u.last_seen_at + GUEST_IDLE_MS),
stats: () => {
@@ -112,8 +151,6 @@ export function startServer(opts: StartOptions) {
},
});
const staticDir = opts.staticDir === undefined ? join(import.meta.dir, '../../web/dist') : opts.staticDir;
const serveStatic = staticDir && existsSync(staticDir);
const server: Server<WsData> = Bun.serve<WsData>({
port: config.port,
@@ -162,6 +199,7 @@ export function startServer(opts: StartOptions) {
clearInterval(sweeper);
gateway.shutdown();
rooms.shutdown();
luck?.stop();
// Bun's stop() promise can stay pending after server-initiated WS closes even though the
// listener is already closed, so bound the wait.
await Promise.race([server.stop(true), Bun.sleep(opts.stopWaitMs ?? 1000)]);
@@ -171,6 +209,15 @@ export function startServer(opts: StartOptions) {
return { server, stop, rooms, users, sessions, db, gateway, settings, roles, purgeIdleGuests };
}
/** The build id the web build wrote into its index.html (`<meta name="bg-build">`, vite.config.ts), or null. */
export function webBuildId(root: string): string | null {
try {
return /<meta name="bg-build" content="([0-9a-f]+)"/.exec(readFileSync(join(root, 'index.html'), 'utf8'))?.[1] ?? null;
} catch {
return null;
}
}
async function serveFile(root: string, pathname: string): Promise<Response> {
const safe = normalize(decodeURIComponent(pathname)).replace(/^(\.\.[/\\])+/, '');
const candidate = join(root, safe);

View File

@@ -0,0 +1,44 @@
/** "업데이트 내용이 있습니다" (docs/07 §11.1): the server tells which web build it serves. */
import { afterEach, expect, test } from 'bun:test';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { webBuildId } from './server';
import { Client, api, boot, guest } from './test-utils';
const running: ReturnType<typeof boot>[] = [];
const clients: Client[] = [];
afterEach(async () => {
for (const c of clients.splice(0)) c.close();
for (const s of running.splice(0)) await s.stop();
});
function webDir(html: string): string {
const dir = mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), 'bg-web-'));
writeFileSync(join(dir, 'index.html'), html);
return dir;
}
test('the build id comes from the meta tag of the served index.html', () => {
expect(webBuildId(webDir('<html><head><meta name="bg-build" content="abc123def456"></head></html>'))).toBe('abc123def456');
expect(webBuildId(webDir('<html><head></head></html>'))).toBeNull();
expect(webBuildId('/nonexistent/dir')).toBeNull();
});
test('/api/version and the socket welcome carry the build', async () => {
const s = boot(undefined, { staticDir: webDir('<html><head><meta name="bg-build" content="0123456789ab"></head></html>') });
running.push(s);
const r = await api(s.base, '/api/version');
expect(r.res.headers.get('cache-control')).toBe('no-store');
expect(r.body).toEqual({ build: '0123456789ab' });
const g = await guest(s.base, '버전확인');
const c = await new Client(s.base, g.cookie, g.id).connect();
clients.push(c);
expect(c.lastOf('welcome')!.build).toBe('0123456789ab');
});
test('without a web build (dev, tests) there is nothing to compare', async () => {
const s = boot();
running.push(s);
expect((await api(s.base, '/api/version')).body).toEqual({ build: null });
});

View File

@@ -0,0 +1,69 @@
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
import type { Server, ServerWebSocket } from 'bun';
import type { RoomManager } from '../rooms/manager';
import { Gateway, type WsData } from './gateway';
function socket(gw: Gateway) {
let data: WsData | undefined;
const server = { upgrade: (_req: Request, o: { data: WsData }) => ((data = o.data), true) } as unknown as Server<WsData>;
gw.upgrade(new Request('http://x/ws'), server, 'u1');
const sent: string[] = [];
let closed: number | null = null;
const ws = {
data: data!,
send: (m: string) => void sent.push(m),
close: (code: number) => void (closed = code),
getBufferedAmount: () => 0,
} as unknown as ServerWebSocket<WsData>;
return { ws, sent, closed: () => closed };
}
describe('gateway flood guard (2026-10-14)', () => {
let spy: ReturnType<typeof spyOn> | null = null;
afterEach(() => spy?.mockRestore());
const chatLine = JSON.stringify({ t: 'chat', text: '도배' });
const gateway = (guard: boolean) => new Gateway({ rooms: {} as RoomManager, me: () => null, now: () => 0, chatFloodGuard: () => guard });
test('도배 방지 켜짐: a flood is cut off before parsing: at most the raw budget of messages is ever parsed', () => {
const gw = gateway(true);
const { ws, closed } = socket(gw);
// Keep the socket open for the whole flood (strikes would close it): only the parse count is under test.
ws.data.strikes = -1e9;
spy = spyOn(JSON, 'parse');
for (let i = 0; i < 1000; i++) gw.handlers.message(ws, '{not json');
// Raw budget = game burst 40 + chat burst 200 (the loop takes a few ms, so barely anything refills).
expect(spy.mock.calls.length).toBeLessThanOrEqual(250);
expect(closed()).toBeNull();
});
test('도배 방지 켜짐: chat past its budget (200 at once) is dropped and a flood closes the socket', () => {
const gw = gateway(true);
const { ws, closed } = socket(gw);
for (let i = 0; i < 1000 && closed() === null; i++) gw.handlers.message(ws, chatLine);
expect(closed()).toBe(4429);
});
test('도배 방지 꺼짐 (기본): chat is never limited; other messages keep their budget', () => {
const gw = gateway(false);
const { ws, closed } = socket(gw);
spy = spyOn(JSON, 'parse');
for (let i = 0; i < 1000; i++) {
gw.handlers.message(ws, chatLine);
gw.handlers.message(ws, JSON.stringify({ t: 'typing', on: i % 2 === 0, ch: 'room' }));
}
expect(spy.mock.calls.length).toBe(2000);
expect(ws.data.strikes).toBe(0);
expect(closed()).toBeNull();
// Junk is still cut off (general budget, then strikes).
for (let i = 0; i < 1000 && closed() === null; i++) gw.handlers.message(ws, '{not json');
expect(closed()).toBe(4429);
});
test('without the setting wired in, the guard is off', () => {
const gw = new Gateway({ rooms: {} as RoomManager, me: () => null });
const { ws, closed } = socket(gw);
for (let i = 0; i < 1000; i++) gw.handlers.message(ws, chatLine);
expect(closed()).toBeNull();
});
});

View File

@@ -8,7 +8,12 @@ import { TokenBucket } from './rate-limit';
export interface WsData {
userId: string;
connId: number;
/** Every message, checked before parsing (room for both budgets below), so a flood never costs a JSON parse each.
* Only while the chat flood guard is on: with it off chat is unlimited, so the raw count cannot be capped. */
rawBucket: TokenBucket;
bucket: TokenBucket;
/** Chat lines and "입력 중" signals have their own budget, so typing fast never eats into (or waits on) game moves. */
chatBucket: TokenBucket;
strikes: number;
room: string | null;
conn: Conn | null;
@@ -21,9 +26,31 @@ export interface GatewayDeps {
log?: (level: 'info' | 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void;
/** A socket closed (the user may have left the site). */
onClose?: (userId: string) => void;
/** Web build being served (pages opened with an older one offer to refresh, docs/07 §11.1). */
build?: () => string | null;
/** Admin setting 채팅 도배 방지 (read per message, so a change applies at once). Off when not given. */
chatFloodGuard?: () => boolean;
}
export const MAX_CONNS_PER_USER = 5;
/**
* Chat budget per socket: far above any typing speed (a line costs up to three messages: 입력 중 on, the line, off),
* only a script flooding the room is cut off.
*/
const CHAT_RATE_PER_SEC = 50;
const CHAT_BURST = 200;
/** Game/other budget per socket. */
const RATE_PER_SEC = 20;
const BURST = 40;
/** Room chat, game chat (마피아·라이어 게임·그림 맞히기 `act` with `type: 'chat'`) and the "입력 중" signal. */
function isChatMessage(m: unknown): boolean {
if (typeof m !== 'object' || m === null) return false;
const { t, a } = m as { t?: unknown; a?: unknown };
if (t === 'chat' || t === 'typing') return true;
return t === 'act' && typeof a === 'object' && a !== null && (a as { type?: unknown }).type === 'chat';
}
const MAX_BUFFERED = 1024 * 1024;
export class Gateway {
@@ -45,7 +72,16 @@ export class Gateway {
upgrade(req: Request, server: Server<WsData>, userId: string): Response | undefined {
if (this.closing) return new Response('restarting', { status: 503 });
if ((this.byUser.get(userId)?.size ?? 0) >= MAX_CONNS_PER_USER) return new Response('too many connections', { status: 429 });
const data: WsData = { userId, connId: this.nextId++, bucket: new TokenBucket(20, 40), strikes: 0, room: null, conn: null };
const data: WsData = {
userId,
connId: this.nextId++,
rawBucket: new TokenBucket(RATE_PER_SEC + CHAT_RATE_PER_SEC, BURST + CHAT_BURST),
bucket: new TokenBucket(RATE_PER_SEC, BURST),
chatBucket: new TokenBucket(CHAT_RATE_PER_SEC, CHAT_BURST),
strikes: 0,
room: null,
conn: null,
};
if (server.upgrade(req, { data })) return undefined;
return new Response('upgrade failed', { status: 400 });
}
@@ -84,6 +120,7 @@ export class Gateway {
serverTime: (this.deps.now ?? Date.now)(),
protocol: PROTOCOL,
activeRoom: this.deps.rooms.activeRoomFor(ws.data.userId),
build: this.deps.build?.() ?? null,
});
},
@@ -93,23 +130,32 @@ export class Gateway {
ws.close(1009, 'message too big');
return;
}
if (!ws.data.bucket.take()) {
const strike = () => {
if (++ws.data.strikes > 50) ws.close(4429, 'rate limited');
return;
}
let parsed: ClientMessage;
};
const guard = this.deps.chatFloodGuard?.() ?? false;
if (guard && !ws.data.rawBucket.take()) return strike();
let json: unknown;
let badJson = false;
try {
const json = JSON.parse(typeof raw === 'string' ? raw : raw.toString());
const r = ClientMessage.safeParse(json);
if (!r.success) {
this.send(ws, { t: 'error', code: 'bad-message', message: '잘못된 요청이에요.' });
return;
}
parsed = r.data;
json = JSON.parse(typeof raw === 'string' ? raw : raw.toString());
} catch {
badJson = true;
}
// Guard off: chat is never limited. Everything else keeps the general budget, and junk is still cut off by strikes.
const chat = !badJson && isChatMessage(json);
const bucket = chat ? (guard ? ws.data.chatBucket : null) : ws.data.bucket;
if (bucket && !bucket.take()) return strike();
if (badJson) {
this.send(ws, { t: 'error', code: 'bad-json', message: '잘못된 요청이에요.' });
return;
}
const r = ClientMessage.safeParse(json);
if (!r.success) {
this.send(ws, { t: 'error', code: 'bad-message', message: '잘못된 요청이에요.' });
return;
}
const parsed: ClientMessage = r.data;
try {
this.dispatch(ws, parsed);
} catch (err) {
@@ -193,6 +239,9 @@ export class Gateway {
case 'removeBot':
e = room.removeBot(u, m.userId);
break;
case 'botLevel':
e = room.setBotLevel(u, m.userId, m.pick);
break;
case 'act':
room.act(u, m.cs, m.a);
return;
@@ -202,6 +251,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;
@@ -211,6 +263,9 @@ export class Gateway {
case 'sync':
room.sendSync(this.connFor(ws));
return;
case 'settled':
room.settled(u, m.seq);
return;
}
if (e) err(e);
}

View File

@@ -0,0 +1,36 @@
/**
* Dev tool: renders every 증강 icon (big and small, light and dark background) to a PNG contact sheet.
* cd apps/web && bun scripts/aug-icon-sheet.tsx [out.png] [ids,comma,separated]
*/
import { renderToStaticMarkup } from 'react-dom/server';
import { chromium } from 'playwright-core';
import { AUGS, AUG_IDS, type AugId } from '@bg/games/yut/augments';
import { AugIcon, GLYPHS } from '../src/games/yut/aug-icons';
const out = process.argv[2] ?? `${process.env.HOME}/.tmp/aug-icons.png`;
const only = process.argv[3]?.split(',').filter(Boolean) as AugId[] | undefined;
const ids = only?.length ? only : [...AUG_IDS];
const cell = (id: AugId) => (
<div className="cell">
<AugIcon id={id} size={72} />
<div className="row">
<div className="light"><AugIcon id={id} size={20} /></div>
<div className="dark"><AugIcon id={id} size={20} /></div>
</div>
<div className={`name${GLYPHS[id] ? '' : ' missing'}`}>{AUGS[id].name}</div>
<div className="id">{id}</div>
</div>
);
const html = `<!doctype html><meta charset="utf-8"><style>
body{margin:0;padding:12px;font-family:sans-serif;background:#f3f4f6}
.grid{display:grid;grid-template-columns:repeat(10,112px);gap:8px}
.cell{display:flex;flex-direction:column;align-items:center;gap:4px;background:#fff;border-radius:8px;padding:6px}
.row{display:flex;gap:4px}.light{background:#fff;padding:3px;border:1px solid #ddd}.dark{background:#111827;padding:3px}
.name{font-size:11px;font-weight:700;text-align:center}.missing{color:#dc2626}.id{font-size:10px;color:#6b7280}
</style><div class="grid">${renderToStaticMarkup(<>{ids.map((id) => <div key={id}>{cell(id)}</div>)}</>)}</div>`;
const browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true });
const page = await browser.newPage({ viewport: { width: 1240, height: 400 }, deviceScaleFactor: 1 });
await page.setContent(html);
await page.screenshot({ path: out, fullPage: true });
await browser.close();
console.log(out, ids.length, 'icons,', ids.filter((id) => !GLYPHS[id]).length, 'missing');

View File

@@ -0,0 +1,43 @@
/** "입력 중…" in 라이어 게임's chat box: `hideBots` leaves out a computer typing its description, never a person typing in the chat. */
import { afterEach, expect, mock, test } from 'bun:test';
import { renderToStaticMarkup } from 'react-dom/server';
import type { RoomView } from '@bg/shared/lite';
// The real socket module needs a browser (document, WebSocket); BotActivity only reads `me` and `typing` from it.
// A plain selector over a test-owned state (a zustand store renders its initial state on the server).
type St = { me: { id: string } | null; typing: Record<string, { ch: 'room' | 'game'; until: number }> };
let st: St = { me: null, typing: {} };
mock.module('../net/socket', () => ({ useRoom: <T,>(sel: (s: St) => T) => sel(st) }));
const { BotActivity } = await import('./BotActivity');
const room = (botActivity: RoomView['botActivity']) =>
({
seats: [
{ user: { id: 'speaker', nickname: '말하는사람' } },
{ user: { id: 'bot:1', nickname: '컴퓨터 1' } },
],
spectators: [],
botActivity,
}) as unknown as RoomView;
const typingAs = (id: string) => (st = { me: { id: 'me' }, typing: { [id]: { ch: 'game', until: Date.now() + 5000 } } });
afterEach(() => (st = { me: null, typing: {} }));
test('설명 차례인 사람이 토론 채팅을 치면 hideBots에 있어도 "입력 중"이 보여요', () => {
typingAs('speaker');
const html = renderToStaticMarkup(<BotActivity room={room(undefined)} only="typing" ch="game" hideBots={['speaker']} />);
expect(html).toContain('말하는사람 입력 중');
});
test('설명 차례인 컴퓨터가 설명을 치는 중이면 채팅 칸에 "입력 중"을 띄우지 않아요', () => {
const r = room({ 'bot:1': 'typing' });
expect(renderToStaticMarkup(<BotActivity room={r} only="typing" ch="game" />)).toContain('컴퓨터 1 입력 중');
expect(renderToStaticMarkup(<BotActivity room={r} only="typing" ch="game" hideBots={['bot:1']} />)).toBe('');
});
test('상태 줄(only="thinking")에는 컴퓨터 "생각 중"만, 입력 중은 없어요', () => {
typingAs('speaker');
const html = renderToStaticMarkup(<BotActivity room={room({ 'bot:1': 'thinking' })} only="thinking" ch="game" />);
expect(html).toContain('컴퓨터 1 생각 중');
expect(html).not.toContain('입력 중');
});

View File

@@ -0,0 +1,34 @@
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 입력 중…", and people
* typing ("💬 고양이 입력 중…", `ch`: the room chat or the game's own public chat). `hideBots`: computers left out
* (라이어 게임: the computer typing its description is not typing in the chat; people's "입력 중" always comes from a chat box).
* Not announced to screen readers: the chat line or the move that follows is.
*/
export function BotActivity({ room, only, ch, hideBots }: { room: RoomView; only?: 'typing' | 'thinking'; ch?: 'room' | 'game'; hideBots?: string[] }) {
const typing = useRoom((s) => s.typing);
const me = useRoom((s) => s.me?.id);
const entries = Object.entries(room.botActivity ?? {}).filter(([id, a]) => (!only || a === only) && !hideBots?.includes(id));
const people = ch && only !== 'thinking' ? 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' ? '입력 중' : '생각 중'}
<span className="bot-dots" />
</span>
))}
{people.map(([id]) => (
<span key={id} data-activity="typing" data-person>
💬 {name(id, '누군가')} 입력 중
<span className="bot-dots" />
</span>
))}
</div>
);
}

View 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;

View File

@@ -3,19 +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 { keepFocus, 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 = (t: string) => socket.send({ t: 'chat', text: t });
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) => {
@@ -33,25 +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" ch="room" />
<div className="emote-row">
{EMOTES.map((id) => (
<button key={id} type="button" onClick={() => socket.send({ t: 'emote', id })}>
@@ -65,8 +66,11 @@ 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();
inputRef.current?.focus();
}}
>
<input
@@ -74,14 +78,20 @@ 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)"
aria-label="메시지"
enterKeyHint="send"
/>
<button className="btn btn-primary btn-sm">보내기</button>
<button className="btn btn-primary btn-sm" {...keepFocus}>
보내기
</button>
</form>
) : (
<p className="muted small">이 방은 채팅을 쓰지 않아요. 반응 버튼은 쓸 수 있어요.</p>
@@ -90,6 +100,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);

View File

@@ -0,0 +1,66 @@
/** 화면 설정 (font size, colours, sound, vibration, tap-to-place), shared by the 설정 page and the 설정 popup. */
import { Link } from 'react-router';
import { useSession } from '../store/session';
import { Sheet } from './ui';
function Seg<T extends string>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
return (
<div className="setting-row">
<strong>{label}</strong>
<div className="segmented" role="group" aria-label={label}>
{options.map(([k, l]) => (
<button key={k} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
{l}
</button>
))}
</div>
</div>
);
}
/** The setting rows only; the caller adds the heading and the box. Changes apply and save at once. */
export function DisplaySettings() {
const settings = useSession((s) => s.settings);
const updateSettings = useSession((s) => s.updateSettings);
return (
<>
<Seg label="글자 크기" value={settings.fontScale} options={[['normal', '보통'], ['large', '크게'], ['xlarge', '아주 크게']]} onChange={(fontScale) => updateSettings({ fontScale })} />
<Seg label="화면 색" value={settings.theme} options={[['auto', '자동'], ['light', '밝게'], ['dark', '어둡게']]} onChange={(theme) => updateSettings({ theme })} />
<Seg label="소리" value={settings.sound ? 'on' : 'off'} options={[['on', '켜기'], ['off', '끄기']]} onChange={(v) => updateSettings({ sound: v === 'on' })} />
<label className="stack" style={{ gap: 4 }}>
<span style={{ fontWeight: 700 }}>
소리 크기 <span className="muted">{settings.volume} (기본 50, 이 기기에만 저장)</span>
</span>
<input type="range" min={0} max={100} step={5} value={settings.volume} aria-label="소리 크기 (0~100)" style={{ accentColor: 'var(--primary)' }} onChange={(e) => updateSettings({ volume: Number(e.target.value) })} />
</label>
<Seg label="진동" value={settings.vibrate ? 'on' : 'off'} options={[['on', '켜기'], ['off', '끄기']]} onChange={(v) => updateSettings({ vibrate: v === 'on' })} />
<Seg
label="돌·카드 놓기"
value={settings.tapConfirm ? 'on' : 'off'}
options={[['on', '두 번 눌러 놓기'], ['off', '한 번에 놓기']]}
onChange={(v) => updateSettings({ tapConfirm: v === 'on' })}
/>
</>
);
}
/**
* 설정 팝업: opens over the current page so a room stays open underneath (no navigation, no leave).
* `account` adds a link to the full 설정 page (nickname, records, logout); rooms leave it out because following it leaves the room.
*/
export function SettingsPopup({ onClose, account }: { onClose: () => void; account?: boolean }) {
return (
<Sheet onClose={onClose} label="설정">
<h2>화면 설정</h2>
<DisplaySettings />
{account && (
<Link className="btn btn-soft btn-block" to="/me" onClick={onClose}>
👤 내 계정 · 기록 보기
</Link>
)}
<button type="button" className="btn btn-secondary btn-block" onClick={onClose}>
닫기
</button>
</Sheet>
);
}

View File

@@ -1,9 +1,11 @@
/** PC top menu (docs/07-ui-ux.md §3.2): 로고·메뉴, 오른쪽에 테마 버튼과 로그인/계정 메뉴. */
import { useEffect, useRef, useState } from 'react';
/** PC top menu (docs/07-ui-ux.md §3.2): 로고·메뉴, 오른쪽에 소리 크기·테마 버튼과 로그인/계정 메뉴. */
import { useCallback, 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';
import { SettingsPopup } from './SettingsPopup';
export function SiteHeader() {
const { me, siteName, role } = useSession();
@@ -21,7 +23,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 />
) : (
@@ -56,14 +61,17 @@ function ThemeToggle() {
);
}
/** 로그인한 뒤: 닉네임(디스코드 연결 시 디스코드 이름) → 누르면 [설정] ([관리자 메뉴]) [로그아웃] 메뉴. */
/** 로그인한 뒤: 닉네임(디스코드 연결 시 디스코드 이름) → 누르면 [설정](팝업) ([관리자 메뉴]) [로그아웃] 메뉴. */
function AccountMenu() {
const me = useSession((s) => s.me)!;
const role = useSession((s) => s.role);
const nav = useNavigate();
const [open, setOpen] = useState(false);
const [confirm, setConfirm] = useState(false);
const [settings, setSettings] = useState(false);
const closeSettings = useCallback(() => setSettings(false), []);
const ref = useRef<HTMLDivElement>(null);
const btn = useRef<HTMLButtonElement>(null);
useEffect(() => {
if (!open) return;
@@ -79,7 +87,7 @@ function AccountMenu() {
return (
<div className="account-menu" ref={ref}>
<button type="button" className="header-user" aria-haspopup="menu" aria-expanded={open} aria-label={`내 계정: ${me.nickname}`} onClick={() => setOpen((o) => !o)}>
<button type="button" ref={btn} className="header-user" aria-haspopup="menu" aria-expanded={open} aria-label={`내 계정: ${me.nickname}`} onClick={() => setOpen((o) => !o)}>
<Avatar user={me} size={36} />
<span className="header-user-name">{me.nickname}</span>
<span aria-hidden className="small muted">
@@ -88,7 +96,8 @@ function AccountMenu() {
</button>
{open && (
<div className="account-menu-list" role="menu" aria-label="내 계정">
<button type="button" role="menuitem" onClick={() => (setOpen(false), nav('/me'))}>
{/* A popup, not a page. The menu item is about to go away, so focus the account button first: the popup returns focus there. */}
<button type="button" role="menuitem" aria-haspopup="dialog" onClick={() => (btn.current?.focus(), setOpen(false), setSettings(true))}>
⚙️ 설정
</button>
{role !== 'user' && (
@@ -101,6 +110,7 @@ function AccountMenu() {
</button>
</div>
)}
{settings && <SettingsPopup onClose={closeSettings} account />}
{confirm && (
<ConfirmSheet
title="로그아웃할까요?"

View 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>
);
}

View File

@@ -1,8 +1,11 @@
/**
* 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 (섯다 instead draws a big outlined
* number in the bottom-left corner, which stays visible when cards overlap);
* 쌍피 / 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 +16,216 @@ 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>
);
}
/** Dark outline around white text (8 directions + soft shadow), readable on both the white and black parts of a card. */
const cornerOutline = (t: number): string =>
[
[-t, -t], [0, -t], [t, -t], [-t, 0], [t, 0], [-t, t], [0, t], [t, t],
]
.map(([x, y]) => `${x}px ${y}px 0 #111827`)
.concat('0 1px 3px rgba(0,0,0,0.6)')
.join(', ');
export function HwatuCard({
card,
size = 'md',
width,
selected,
dimmed,
highlight,
showMonth = true,
monthStyle = 'badge',
onClick,
disabled,
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;
/** 'badge': small dark circle top-right. 'corner': big white outlined number bottom-left (섯다). */
monthStyle?: 'badge' | 'corner';
onClick?: () => void;
/** Keeps the card a (disabled) button while it can't be clicked, so switching on/off doesn't remount it (no replayed deal animation). */
disabled?: boolean;
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',
cursor: onClick && !disabled ? '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}
disabled={onClick ? disabled : undefined}
aria-label={card.name}
aria-pressed={onClick && !disabled ? !!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 && monthStyle === 'corner' && (
<span
aria-hidden
style={{
position: 'absolute',
left: Math.round(w * 0.08),
bottom: Math.round(w * 0.06),
color: '#fff',
fontSize: Math.max(12, Math.round(8 + w * 0.26)),
fontWeight: 900,
lineHeight: 1,
letterSpacing: '-0.04em',
textShadow: cornerOutline(Math.max(1, Math.round(w * 0.025))),
fontFamily: 'Pretendard Variable, sans-serif',
pointerEvents: 'none',
}}
>
{card.month}
</span>
)}
{showMonth && card.month > 0 && monthStyle === 'badge' && (
<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>
);
}

View File

@@ -1,6 +1,20 @@
/** Trump card drawn in SVG (no image assets). Big corner index for readability on PC and phones. */
/**
* Trump card drawn in SVG. Big corner index for readability on PC and phones. Number cards and the back are drawn here;
* J/Q/K and the two jokers show real card artwork by Dmitry Fomin (Wikimedia Commons, CC0 — ./court/ATTRIBUTION.txt),
* bundled from our own origin as small WebP files that load only when such a card is on screen.
*/
import type { CSSProperties } from 'react';
/** Credit for the court/joker artwork (CC0 needs none, but we say thanks); shown in the rules of the games using these cards. */
export const PLAYING_CARD_CREDIT =
'트럼프 그림카드(J·Q·K)·조커 그림: Dmitry Fomin — Wikimedia Commons "SVG English pattern playing cards", "Atlas deck joker", CC0 1.0(퍼블릭 도메인). 그림 부분만 잘라 작게 줄여 썼어요.';
/**
* URL of the court/joker picture ("JS".."KC", "X1" black joker, "X2" red joker). Vite turns this pattern into hashed
* /assets/ files; in tests it is just a file URL.
*/
export const courtSrc = (id: string): string => new URL(`./court/${id}.webp`, import.meta.url).href;
const SUIT_SYMBOL: Record<string, string> = { S: '♠', H: '♥', D: '◆', C: '♣' };
const SUIT_KO: Record<string, string> = { S: '스페이드', H: '하트', D: '다이아', C: '클로버' };
const RANK_LABEL: Record<string, string> = { T: '10', J: 'J', Q: 'Q', K: 'K', A: 'A' };
@@ -13,6 +27,8 @@ export interface PlayingCardProps {
/** e.g. "AS", "TD", "X1" (joker). null = face down. */
card: string | null;
size?: CardSize;
/** Exact width in px (overrides `size`). */
width?: number;
selected?: boolean;
dimmed?: boolean;
highlight?: boolean;
@@ -30,8 +46,8 @@ export function cardAria(card: string | null): string {
return `${SUIT_KO[card[1]!]} ${FACE_KO[r] ?? RANK_LABEL[r] ?? r}`;
}
export function PlayingCard({ card, size = 'md', selected, dimmed, highlight, onClick, title, style, fourColor }: PlayingCardProps) {
const w = WIDTH[size];
export function PlayingCard({ card, size = 'md', width, selected, dimmed, highlight, onClick, title, style, fourColor }: PlayingCardProps) {
const w = width ?? WIDTH[size];
const h = Math.round(w * 1.4);
const lift = selected ? -Math.round(w * 0.22) : 0;
const common: CSSProperties = {
@@ -74,28 +90,26 @@ export function PlayingCard({ card, size = 'md', selected, dimmed, highlight, on
<Tag style={{ ...common, ...btnReset }} onClick={onClick} aria-label={title ?? cardAria(card)} aria-pressed={onClick ? !!selected : undefined} title={title}>
<svg viewBox="0 0 100 140" width={w} height={h} aria-hidden>
<rect x="1" y="1" width="98" height="138" rx="9" fill="#fffef9" stroke={selected ? '#2563eb' : '#9ca3af'} strokeWidth={selected ? 5 : 2} />
<text x="9" y="33" fontSize="30" fontWeight="800" fill={color} fontFamily="Pretendard Variable, sans-serif">
{label}
</text>
<text x="11" y="60" fontSize="26" fill={color}>
{sym}
</text>
{joker ? (
<text x="50" y="98" fontSize="22" fontWeight="800" textAnchor="middle" fill={color}>
JOKER
</text>
<image href={courtSrc(card === 'X1' ? 'X1' : 'X2')} x="22" y="30" width="72" height="104" preserveAspectRatio="xMidYMid meet" />
) : 'JQK'.includes(rank) ? (
<>
<rect x="30" y="44" width="56" height="78" rx="6" fill={color} opacity="0.1" />
<text x="58" y="100" fontSize="44" fontWeight="800" textAnchor="middle" fill={color}>
{rank}
</text>
{/* picture frame like a real court card, with a notch at top-left so the big index stays readable */}
<image href={courtSrc(rank + suit)} x="10" y="5" width="80" height="130" preserveAspectRatio="xMidYMid slice" />
<path d="M10 5H36V65H10Z" fill="#fffef9" />
<path d="M36 5H90V135H10V65H36Z" fill="none" stroke={color} strokeOpacity="0.55" strokeWidth="1.2" />
</>
) : (
<text x="60" y="108" fontSize="54" textAnchor="middle" fill={color}>
{sym}
</text>
)}
<text x="9" y="33" fontSize="30" fontWeight="800" fill={color} fontFamily="Pretendard Variable, sans-serif">
{label}
</text>
<text x="11" y="60" fontSize="26" fill={color}>
{sym}
</text>
</svg>
</Tag>
);

View File

@@ -0,0 +1,21 @@
트럼프 그림카드·조커 그림 출처 (Playing card court and joker artwork)
JS JH JD JC / QS QH QD QC / KS KH KD KC .webp (J·Q·K 12장, 파일 이름 = 게임 엔진의 카드 id, 랭크+무늬)
- 원본: Wikimedia Commons "Category:SVG English pattern playing cards"
https://commons.wikimedia.org/wiki/Category:SVG_English_pattern_playing_cards
File:English pattern jack of spades.svg ~ File:English pattern king of clubs.svg (2026-10-13 받음)
- 만든 사람: Dmitry Fomin (Дмитрий Фомин), https://commons.wikimedia.org/wiki/User:Dmitry_Fomin
- 라이선스: CC0 1.0 (퍼블릭 도메인 헌정, https://creativecommons.org/publicdomain/zero/1.0/)
X1.webp (검은 조커), X2.webp (빨간 조커)
- 원본: Wikimedia Commons
https://commons.wikimedia.org/wiki/File:Atlas_deck_joker_black.svg
https://commons.wikimedia.org/wiki/File:Atlas_deck_joker_red.svg (2026-10-13 받음)
- 만든 사람: Dmitry Fomin (Дмитрий Фомин)
- 라이선스: CC0 1.0
바꾼 점: 원본 SVG(360×540)를 4배로 그린 뒤 그림카드는 파란 테두리 안쪽 그림만, 조커는 광대 그림만 잘라
(모서리 글자·러시아어 "ДЖОКЕР" 글자는 뺌) 높이 282px WebP(품질 80)로 줄이고, 흰 바탕을 카드 종이색(#fffef9)으로 칠했다.
CC0이라 출처 표시 의무는 없지만 고마움의 뜻으로 적어 둔다. 숫자 카드·뒷면·모서리 글자는 PlayingCard.tsx 가 직접 그린다.

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 26 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 19 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 51 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 56 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 34 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 28 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 26 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 27 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 29 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 21 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 18 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 20 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 12 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 50 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 27 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 29 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 23 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 54 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 27 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 24 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 20 KiB

View 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

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 28 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 10 KiB

View 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

View 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

Some files were not shown because too many files have changed in this diff Show More