방 설정 "컴퓨터 채팅": 컴퓨터가 혼자 말하는 건 방장이 켤 때만(기본 끄기), 마피아는 항상 켜짐

- RoomConfig/RoomView.botChat, config 메시지에 botChat. 새 방·옛 방 모두 끄기.
- BotBrain: 꺼져 있으면 도발·반응·대답·시작 인사·끝 인사 안 함, 모델 미리 올리기도 안 함.
  바퀴벌레 포커 진짜/블러핑 판단은 그대로, 한마디만 뺌.
- BOT_CHAT_REQUIRED(마피아): 설정과 상관없이 항상 켜짐, 설정 칸에 "항상 켜짐" 표시.
- 대기실 설정에 컴퓨터 채팅 켜기/끄기(컴퓨터 상대가 있는 게임만).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-12 21:59:30 +09:00
parent bd179c7a43
commit 2ec622ebf6
9 changed files with 113 additions and 13 deletions

View File

@@ -115,7 +115,7 @@ describe('rooms with the model', () => {
rooms.push(room);
const a = h.conn('A');
room.join(a, 'player');
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } });
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' }, botChat: true });
expect(room.start('A')).toBeNull();
await settle();
room.act('A', 1, { type: 'place', x: 7, y: 7 });
@@ -139,6 +139,7 @@ describe('rooms with the model', () => {
rooms.push(room);
const a = h.conn('A');
room.join(a, 'player');
room.configure('A', { botChat: true });
expect(room.start('A')).toBeNull();
room.chat('A', '컴퓨터 1 오목 잘해?');
for (let i = 0; i < 20 && !a.msgs.some((m) => m.t === 'chat' && (m as { text: string }).text.startsWith('저요?')); i++) await settle();
@@ -172,6 +173,7 @@ describe('rooms with the model', () => {
rooms.push(room);
const a = h.conn(`A${attempt}`);
room.join(a, 'player');
room.configure(`A${attempt}`, { botChat: true });
expect(room.start(`A${attempt}`)).toBeNull();
const st = () => room.game!.state as { round: { claim: string | null; card: string | null; starter: string } };
if (!isBotId(st().round.starter)) continue;
@@ -190,6 +192,59 @@ describe('rooms with the model', () => {
expect(checked).toBe(true);
});
test('컴퓨터 채팅 off (the default): computers never talk on their own — no taunts, answers, greetings or end words', async () => {
const h = harness(() => '흐음, 여기 두면 아프겠는데?', () => 0);
const room = h.manager.createPractice('A', 'omok') as Room;
rooms.push(room);
const a = h.conn('A');
room.join(a, 'player');
expect(room.roomView().botChat).toBe(false);
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } });
expect(room.start('A')).toBeNull();
await settle();
room.chat('A', '컴퓨터 1 오목 잘해?');
for (let i = 0; i < 3; i++) {
room.act('A', i + 1, { type: 'place', x: [0, 14, 0][i]!, y: [0, 14, 14][i]! });
room.bots.fire();
for (let k = 0; k < 20 && (room.game!.state as { moves: unknown[] }).moves.length < 2 * (i + 1); k++) await settle();
}
expect((room.game!.state as { moves: unknown[] }).moves.length).toBe(6);
expect(a.msgs.some((m) => m.t === 'chat' && (m as { from: { id: string } | null }).from && isBotId((m as { from: { id: string } }).from.id))).toBe(false);
// The model isn't even warmed up: nothing in this game uses it.
expect(h.prompts).toHaveLength(0);
});
test('컴퓨터 채팅 off: in 바퀴벌레 포커 the model still decides truth or bluff, the computer just says nothing', async () => {
let checked = false;
for (let attempt = 0; attempt < 12 && !checked; attempt++) {
const h = harness((_u, body) => (body.format ? JSON.stringify({ bluff: false, say: '이건 진짜야, 믿어봐~' }) : '흠'));
const room = h.manager.createPractice(`B${attempt}`, 'cockroach-poker') as Room;
rooms.push(room);
const a = h.conn(`B${attempt}`);
room.join(a, 'player');
expect(room.start(`B${attempt}`)).toBeNull();
const st = () => room.game!.state as { round: { claim: string | null; card: string | null; starter: string } };
if (!isBotId(st().round.starter)) continue;
for (let i = 0; i < 30 && !st().round.claim; i++) {
room.bots.fire();
await settle();
}
expect(st().round.claim).toBe(st().round.card!.replace(/-\d+$/, ''));
expect(a.msgs.some((m) => m.t === 'chat')).toBe(false);
checked = true;
}
expect(checked).toBe(true);
});
test('마피아 needs its computers to talk: 컴퓨터 채팅 is always on there', () => {
const h = harness(() => '흠');
const room = h.manager.createPractice('A', 'mafia') as Room;
rooms.push(room);
room.join(h.conn('A'), 'player');
room.configure('A', { botChat: false });
expect(room.roomView().botChat).toBe(true);
});
test('마피아: a computer says its planned line in its own words; a line claiming a role is thrown away', async () => {
let n = 0;
const h = harness(() => (n++ % 2 === 0 ? '안녕하세요~ 오늘 마피아 꼭 잡아봐요!' : '저 경찰이에요 믿어주세요'));

View File

@@ -9,6 +9,7 @@
* 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';
@@ -31,6 +32,11 @@ export interface BrainRoom {
recentChat(): { from: string; text: string }[];
/** 똑똑한 편 (존댓말) or 허술한 편 (반말), docs/09 §9.1. */
smart(bot: string): boolean;
/**
* The computers may chat on their own (room setting "컴퓨터 채팅"; always on in 마피아). Off: no small talk,
* reactions, answers, greetings or end-of-game words — they just play (still showing "생각 중…").
*/
chatty(): boolean;
now(): number;
}
@@ -128,7 +134,7 @@ export class BotBrain {
if (!type || type === 'chat' || type === 'say' || type === 'reaction' || type === 'ping' || type === 'timeout') return;
this.happened.push(`${this.room.nameOf(actor)} ${ACTION_KO[type] ?? '행동함'}`);
if (this.happened.length > 12) this.happened.shift();
if (!this.enabled() || this.room.bots().includes(actor) || this.room.gameId() === 'mafia') return;
if (!this.enabled() || !this.room.chatty() || this.room.bots().includes(actor) || this.room.gameId() === 'mafia') return;
const bots = this.room.bots().filter((b) => this.canTalk(b, 10_000, 30_000));
if (!bots.length || this.random() > 0.12) return;
const bot = bots[Math.floor(this.random() * bots.length)]!;
@@ -152,9 +158,10 @@ export class BotBrain {
const r = await this.cockroachBluff(bot, a, view);
if (r) {
act = r.action;
line = r.say;
// Chat off: the model still decides truth or bluff, the computer just hands the card over without a word.
line = this.room.chatty() ? r.say : null;
}
} else if (this.canTalk(bot) && this.random() < temperOf(bot).talk) {
} else if (this.room.chatty() && this.canTalk(bot) && this.random() < temperOf(bot).talk) {
const type = String(a.type ?? '');
line = await writeLine(this.llm, this.request(bot, this.situation(), `나는 지금 "${ACTION_KO[type] ?? '내 수'}"를 하려 한다. 이 수를 두며 상대에게 던지는 도발이나 심리전 한마디.`));
}
@@ -195,7 +202,7 @@ export class BotBrain {
/** People chatting: a named computer answers; otherwise sometimes one of them joins in. */
onHumanChat(from: string, text: string): void {
if (!this.enabled() || this.room.gameId() === 'mafia') return;
if (!this.enabled() || !this.room.chatty() || this.room.gameId() === 'mafia') return;
const bots = this.room.bots();
const named = bots.find((b) => {
const n = /^컴퓨터 (\d+)$/.exec(this.room.nameOf(b))?.[1];
@@ -212,9 +219,10 @@ export class BotBrain {
onGameStart(): void {
this.happened = [];
// A game with computers and people: make sure the model is loaded before anyone talks.
if (this.llm?.available() && this.room.humans().length && this.room.bots().length) void this.llm.warm();
if (!this.enabled() || this.room.gameId() === 'mafia' || this.random() > 0.7) return;
// A game with computers and people where the model will be used: make sure it is loaded before anyone talks.
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();
if (!this.enabled() || !this.room.chatty() || this.room.gameId() === 'mafia' || this.random() > 0.7) return;
const bots = this.room.bots();
const bot = bots[Math.floor(this.random() * bots.length)];
if (!bot) return;
@@ -226,7 +234,7 @@ export class BotBrain {
/** The game ended: a computer that won gloats a little, or one that lost takes it with a word. */
onGameEnd(ranking: string[][]): void {
if (!this.llm?.available() || !this.room.humans().length || this.room.gameId() === 'mafia' || this.random() > 0.85) return;
if (!this.llm?.available() || !this.room.chatty() || !this.room.humans().length || this.room.gameId() === 'mafia' || this.random() > 0.85) 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)];

View File

@@ -115,6 +115,7 @@ export class RoomManager {
allowSpectators: true,
chatEnabled: site?.chatEnabledDefault ?? true,
chatFilter: site?.chatFilterDefault ?? true,
botChat: false,
graceSec: site?.graceSec ?? 60,
};
const code = this.newCode();

View File

@@ -4,7 +4,7 @@
*/
import { ulid } from 'ulid';
import { SeededRng, createSeed, secureRandom, seedToHex, type AnyGameDefinition, type ChaChaSeed, type GameResult, type RngState } from '@bg/engine';
import { botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type BotPick, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared';
import { botChatRequired, botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type BotPick, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared';
import { botPersona } from '@bg/games/bots';
import { luckApplies, shufflesFor, type LuckJob } from '@bg/games/bots/luck';
import { sha256Hex } from '../auth/sessions';
@@ -29,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;
}
@@ -189,6 +191,7 @@ export class Room {
},
recentChat: () => this.chatLog.slice(-8).map((m) => ({ from: m.from?.nickname ?? '누군가', text: m.text })),
smart: (bot) => botPersona(bot, this.profile(bot).base).smart,
chatty: () => this.botChatOn(),
now: this.now,
},
deps.ai ?? null,
@@ -222,6 +225,11 @@ export class Room {
);
}
/** The computers' own chat: the room setting, or always where the game needs it (마피아). */
private botChatOn(): boolean {
return botChatRequired(this.config.gameId) || this.config.botChat === true;
}
get def(): AnyGameDefinition {
const d = this.deps.games[this.config.gameId];
if (!d) throw new Error(`unknown game ${this.config.gameId}`);
@@ -411,6 +419,7 @@ export class Room {
allowSpectators: this.config.allowSpectators,
chatEnabled: this.config.chatEnabled,
chatFilter: this.config.chatFilter,
botChat: this.botChatOn(),
seats,
spectators: [...this.spectators].map(pub),
status: this.status,
@@ -689,7 +698,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.

View File

@@ -1,7 +1,7 @@
/** 방: 대기실 ↔ 게임 ↔ 결과를 한 주소에서 전환 (docs/06 §5–§9). */
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { Link, useNavigate, useParams } from 'react-router';
import { BOT_BANDS, BOT_PICKS, BOT_PICK_LABEL, bandOf, botsAllowed, formatRoomCode, isBotId, luckLabel, type PublicUser, type RoomView } from '@bg/shared/lite';
import { BOT_BANDS, BOT_PICKS, BOT_PICK_LABEL, bandOf, botChatRequired, botsAllowed, formatRoomCode, isBotId, luckLabel, type PublicUser, type RoomView } from '@bg/shared/lite';
import { Avatar, CodeLabel, ConfirmSheet, CopyButton, ShareButton, Sheet, TopBar } from '../components/ui';
import { GuestWarning, NicknameForm } from '../components/NicknameForm';
import { GameNotice, gameName } from '../components/GameNotice';
@@ -581,6 +581,21 @@ function SettingsForm({ room, ui, inline, readOnly, onDone }: { room: RoomView;
<strong>채팅</strong>
{readOnly ? <ReadOnlyControls>{seg(room.chatEnabled, () => {}, '켜기', '끄기')}</ReadOnlyControls> : seg(room.chatEnabled, (chatEnabled) => socket.send({ t: 'config', chatEnabled }), '켜기', '끄기')}
</div>
{botsAllowed(room.gameId) && (
<div className="stack" style={{ gap: 6 }}>
<strong>컴퓨터 채팅</strong>
{botChatRequired(room.gameId) ? (
<p className="muted small" style={{ margin: 0 }}>
항상 켜짐 · 이 게임은 컴퓨터도 말해야 할 수 있어요
</p>
) : readOnly ? (
<ReadOnlyControls>{seg(room.botChat, () => {}, '켜기', '끄기')}</ReadOnlyControls>
) : (
seg(room.botChat, (botChat) => socket.send({ t: 'config', botChat }), '켜기', '끄기')
)}
{!botChatRequired(room.gameId) && <span className="muted small">켜면 컴퓨터가 게임하면서 먼저 말을 걸고, 채팅에 대답해요.</span>}
</div>
)}
</div>
{!inline && (
<button className="btn btn-primary btn-block" onClick={onDone}>

View File

@@ -119,7 +119,8 @@ interface Room {
- 성격: 컴퓨터 id로 정해지는 5가지 — 도발형·허세형·차분형·수다형·소심형 — 와 말투(똑똑한 편 존댓말, 허술한 편 반말).
- 난이도: 컴퓨터마다 1~60단계(§12, 보안 난수)이고, 오목·체스·장기·오델로·바둑에서는 단계에 따라 가끔 비슷한 다른 수를 두거나 실수한다. 확률과 기준은 09 §9.1. 카드·주사위 게임은 운(04 §5.1)이 배분에 영향을 준다.
- 보이는 행동: 수를 고르는 동안 "🤖 컴퓨터 1 생각 중…", 말할 때는 그 줄을 치는 만큼(글자 수 × 컴퓨터마다 다른 타자 속도, 0.9~6.5초) "💬 입력 중…"이 보인 뒤 채팅이 올라가고, 잠깐 뒤 수를 둔다(상태 줄과 채팅 칸, `RoomView.botActivity`).
- 말하는 때: 자기 수와 함께 도발·심리전 한마디(성격별 14~38%, 방 전체 8초·컴퓨터마다 20초 간격), 사람의 수에 가끔 반응(12%), 사람이 이름을 부르거나 말을 걸면 대답(이름 부르면 꼭, 아니면 40%), 시작 인사, 끝나면 이긴 컴퓨터가 놀리거나 진 컴퓨터가 아쉬워함.
- 방 설정 "컴퓨터 채팅"(2026-10-12): 방장이 켜야만 아래처럼 혼자 말한다(새 방 기본은 끄기, 저장해 둔 옛 방도 끄기로 읽음). 끄면 컴퓨터는 말없이 두기만 하고("생각 중…"은 그대로), 바퀴벌레 포커의 진짜/블러핑 판단은 모델이 계속 하되 한마디는 하지 않는다. 컴퓨터가 말해야 게임이 되는 마피아는 항상 켜짐(`BOT_CHAT_REQUIRED`, 설정 칸에 "항상 켜짐"으로 보임). `RoomConfig.botChat`·`RoomView.botChat`.
- 말하는 때(컴퓨터 채팅을 켰을 때): 자기 수와 함께 도발·심리전 한마디(성격별 14~38%, 방 전체 8초·컴퓨터마다 20초 간격), 사람의 수에 가끔 반응(12%), 사람이 이름을 부르거나 말을 걸면 대답(이름 부르면 꼭, 아니면 40%), 시작 인사, 끝나면 이긴 컴퓨터가 놀리거나 진 컴퓨터가 아쉬워함.
- 심리전 판단: 바퀴벌레 포커에서 카드를 건넬 때 진짜를 말할지 블러핑할지를 모델이 정하고, 그걸 파는 한마디를 한다(실제 카드 이름이 들어간 말은 버림). 마피아는 컴퓨터가 계획한 대사(의심 지목·반박·반론 등)를 모델이 자기 말로 바꾼다. 모델에게 그 컴퓨터의 직업은 알려 주지 않고, "저 경찰이에요"·"나 마피아" 같은 직업 주장이 나오면 버리고 원래 대사를 쓴다.
- 안전: 한 줄만, 40자 안팎, 한국어만(외국 문자·영어 단어·"AI"류 말 거름), 고운 말 필터·링크·전화번호 차단, 숨은 정보는 말하지 않게 지시.
- 모델이 없거나 바쁘면 전처럼 조용히 둔다(게임은 모델을 기다리지 않는다).

View File

@@ -56,6 +56,14 @@ export const PRACTICE_PLAYERS: Readonly<Record<string, number>> = { mafia: 6 };
export const botsAllowed = (gameId: string): boolean => BOT_GAMES.includes(gameId);
/**
* Games where computers must talk to play at all (마피아 토론): their computers always speak, whatever the room's
* "컴퓨터 채팅" setting says. In every other game the computers' small talk is off unless the host turns it on.
*/
export const BOT_CHAT_REQUIRED: readonly string[] = ['mafia'];
export const botChatRequired = (gameId: string): boolean => BOT_CHAT_REQUIRED.includes(gameId);
/**
* Computer levels 1~60 (docs/09-game-engine.md §9.1): 1~20 쉬움, 21~40 보통, 41~60 어려움. The host can pick a band
* for each computer after adding it; the exact level inside the band is drawn at random and stays hidden until the

View File

@@ -25,6 +25,7 @@ export const ClientMessage = z.discriminatedUnion('t', [
allowSpectators: z.boolean().optional(),
chatEnabled: z.boolean().optional(),
chatFilter: z.boolean().optional(),
botChat: z.boolean().optional(),
}),
z.object({ t: z.literal('start') }),
z.object({ t: z.literal('kick'), userId }),

View File

@@ -43,6 +43,8 @@ export interface RoomView {
allowSpectators: boolean;
chatEnabled: boolean;
chatFilter: boolean;
/** Computers chat on their own (small talk, reactions, answers). Always on where the game needs it (`botChatRequired`). */
botChat: boolean;
seats: (SeatView | null)[];
spectators: PublicUser[];
status: RoomStatus;