- packages/games/src/bang: 뱅!(4~7명) 규칙 모듈. 카드 80장·캐릭터 16종 데이터, 거리/사거리, 효과·반응 스택(뱅!/개틀링/인디언!/결투/잡화점/빈사/킷 칼슨/choose2), 다이너마이트·감옥 판정, 처치 보상·보안관 벌칙·벌처 샘, 승리 판정, 역할·손패·덱 비공개 view, onTimeout/onLeave, legalActions·secretsOf. 하우스 룰 옵션 4종. - 테스트 62개: 문서 §10 시나리오 전부, 시드 1,000개 4~7명 무작위 대국(카드 총수 보존, 생명 범위, 정보 유출, onTimeout 합법, 결정성) + 엔진 randomPlayout 실행, 재생 결정성. - apps/web/src/games/bang: 원형 테이블(생명 탄환·장착·거리·역할 배지), 꾹 눌러 보는 내 역할 카드, 카드 선택 → 대상 강조 → 확인, 반응 시트와 타이머, 기록·카드 도감, PC/휴대폰, 라이트/다크. - 등록: GAMES, 카탈로그(available), 웹 레지스트리, 아이콘(UPCOMING에서 '뱅' 제거). - e2e: bang 플랜(PC 방장 + 휴대폰 3명, 반응 25초, 실제 턴 10번: 뱅!·기타 카드·반응·버리기). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
275 lines
14 KiB
TypeScript
275 lines
14 KiB
TypeScript
/** 뱅! legality checks (docs/games/bang.md §5.2–§5.4, §8.2) and what the view needs from them. */
|
||
import { fail, ok, type PlayerId, type Validation } from '@bg/engine';
|
||
import { cardById, isBlue, kindOf, type CardKind } from './cards';
|
||
import { distance, hasEquip, rangeOf } from './distance';
|
||
import { barrelLeft, beerWorks, drawChoice, findPlayer, is, living, P, reactionOf, responder } from './effects';
|
||
import type { BangAction, BangState, PlayAction, PlayOption, PlayerState, Prompt, Reaction, TargetOption } from './types';
|
||
|
||
const TARGETED: CardKind[] = ['bang', 'panic', 'catBalou', 'duel', 'jail'];
|
||
export const needsTarget = (k: CardKind): boolean => TARGETED.includes(k);
|
||
|
||
export const unlimitedBang = (p: PlayerState): boolean => is(p, 'willy') || hasEquip(p, 'volcanic');
|
||
|
||
/** Cards that answer a 뱅! (빗나감!, or 뱅! for Calamity Janet). */
|
||
export const missedLike = (p: PlayerState, id: string): boolean => kindOf(id) === 'missed' || (is(p, 'calamity') && kindOf(id) === 'bang');
|
||
/** Cards that answer 인디언! / 결투 (뱅!, or 빗나감! for Calamity Janet). */
|
||
export const bangLike = (p: PlayerState, id: string): boolean => kindOf(id) === 'bang' || (is(p, 'calamity') && kindOf(id) === 'missed');
|
||
|
||
export const myPlayTime = (s: BangState, p: PlayerId): boolean => !s.winner && s.turn.player === p && s.turn.phase === 'play' && s.reactions.length === 0;
|
||
|
||
/** null = the play is legal; otherwise the Korean reason. */
|
||
export function checkPlay(s: BangState, actor: PlayerId, a: PlayAction): string | null {
|
||
const p = P(s, actor);
|
||
if (s.turn.player !== actor || s.turn.phase !== 'play') return '지금은 카드를 낼 수 없어요.';
|
||
if (s.reactions.length > 0) return '다른 사람의 반응을 기다리고 있어요.';
|
||
if (!p.hand.includes(a.cardId)) return '손에 없는 카드예요.';
|
||
const card = cardById(a.cardId);
|
||
if (a.as !== undefined) {
|
||
if (!is(p, 'calamity')) return '캘러미티 자넷만 카드를 바꿔 낼 수 있어요.';
|
||
if (a.as !== 'bang' || card.kind !== 'missed') return '내 차례에는 빗나감!을 뱅!으로만 바꿔 낼 수 있어요.';
|
||
}
|
||
const kind: CardKind = a.as ?? card.kind;
|
||
if (kind === 'missed') return '빗나감!은 공격을 받았을 때만 낼 수 있어요.';
|
||
if (a.targetCard !== undefined && kind !== 'panic' && kind !== 'catBalou') return '이 카드는 카드를 고르지 않아요.';
|
||
if (!needsTarget(kind)) {
|
||
if (a.target !== undefined) return '이 카드는 대상을 고르지 않아요.';
|
||
} else {
|
||
if (!a.target) return '대상을 골라 주세요.';
|
||
const t = findPlayer(s, a.target);
|
||
if (!t) return '없는 플레이어예요.';
|
||
if (!t.alive) return '이미 쓰러진 사람이에요.';
|
||
}
|
||
const t = a.target ? P(s, a.target) : null;
|
||
switch (kind) {
|
||
case 'bang': {
|
||
if (t!.id === actor) return '자기 자신은 쏠 수 없어요.';
|
||
if (s.turn.bangsPlayed >= 1 && !unlimitedBang(p)) return '이번 턴에는 뱅!을 이미 썼어요.';
|
||
const d = distance(s, actor, t!.id);
|
||
const r = rangeOf(p);
|
||
if (d > r) return `사거리가 닿지 않아요(거리 ${d}, 사거리 ${r}).`;
|
||
return null;
|
||
}
|
||
case 'beer':
|
||
if (s.options.beerAtFullHealth) return null;
|
||
if (!beerWorks(s)) return '두 명만 남으면 맥주는 효과가 없어요.';
|
||
if (p.life >= p.maxLife) return '생명이 가득 차서 맥주를 쓸 수 없어요.';
|
||
return null;
|
||
case 'panic':
|
||
case 'catBalou': {
|
||
const self = t!.id === actor;
|
||
if (self && !s.options.selfTargetCatBalou) return '자기 자신에게는 쓸 수 없어요.';
|
||
const tc = a.targetCard;
|
||
if (!tc) return '가져올 카드를 골라 주세요.';
|
||
if (tc === 'hand') {
|
||
if (self) return '내 손패에는 쓸 수 없어요.';
|
||
if (t!.hand.length === 0) return '손패가 없는 사람이에요.';
|
||
} else if (!t!.inPlay.includes(tc)) return '그 사람 앞에 없는 카드예요.';
|
||
if (kind === 'panic' && !self) {
|
||
const d = distance(s, actor, t!.id);
|
||
if (d > 1) return `패닉!은 거리 1인 사람에게만 쓸 수 있어요(거리 ${d}).`;
|
||
}
|
||
return null;
|
||
}
|
||
case 'duel':
|
||
return t!.id === actor ? '자기 자신과는 결투할 수 없어요.' : null;
|
||
case 'jail':
|
||
if (t!.id === actor) return '자기 자신은 감옥에 넣을 수 없어요.';
|
||
if (t!.role === 'sheriff') return '보안관은 감옥에 넣을 수 없어요.';
|
||
if (hasEquip(t!, 'jail')) return '이미 감옥에 있는 사람이에요.';
|
||
return null;
|
||
default:
|
||
if (isBlue(kind) && hasEquip(p, kind)) return '같은 카드를 이미 앞에 놓았어요.';
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/** Sid Ketchum may heal on his own turn or while answering a reaction aimed at him. */
|
||
export function sidHealContext(s: BangState, actor: PlayerId): boolean {
|
||
const p = P(s, actor);
|
||
if (!is(p, 'sid') || !p.alive || s.winner) return false;
|
||
const r = reactionOf(s, actor);
|
||
if (r) return r.kind === 'bang' || r.kind === 'indians' || r.kind === 'duel' || r.kind === 'dying';
|
||
return s.turn.player === actor && s.reactions.length === 0 && (s.turn.phase === 'play' || s.turn.phase === 'discard');
|
||
}
|
||
|
||
function distinctInHand(p: PlayerState, ids: string[]): string | null {
|
||
if (new Set(ids).size !== ids.length) return '같은 카드를 두 번 고를 수 없어요.';
|
||
if (ids.some((id) => !p.hand.includes(id))) return '손에 없는 카드예요.';
|
||
return null;
|
||
}
|
||
|
||
function checkRespond(s: BangState, p: PlayerState, r: Reaction, ids: string[]): string | null {
|
||
const bad = distinctInHand(p, ids);
|
||
if (bad) return bad;
|
||
switch (r.kind) {
|
||
case 'bang':
|
||
if (ids.length !== r.needed) return r.needed > 1 ? `빗나감! ${r.needed}장을 한꺼번에 내야 막을 수 있어요.` : '빗나감! 1장을 골라 주세요.';
|
||
if (!ids.every((id) => missedLike(p, id))) return is(p, 'calamity') ? '빗나감!이나 뱅!만 낼 수 있어요.' : '빗나감!만 낼 수 있어요.';
|
||
return null;
|
||
case 'indians':
|
||
case 'duel':
|
||
if (ids.length !== 1) return '뱅! 1장을 골라 주세요.';
|
||
if (!bangLike(p, ids[0]!)) return is(p, 'calamity') ? '뱅!이나 빗나감!만 낼 수 있어요.' : '뱅!만 낼 수 있어요.';
|
||
return null;
|
||
case 'dying': {
|
||
if (!beerWorks(s)) return '두 명만 남으면 맥주로 살아날 수 없어요.';
|
||
const need = 1 - p.life;
|
||
if (ids.length !== need) return `맥주 ${need}장이 필요해요.`;
|
||
if (!ids.every((id) => kindOf(id) === 'beer')) return '맥주만 낼 수 있어요.';
|
||
return null;
|
||
}
|
||
default:
|
||
return '지금은 카드를 낼 수 없어요.';
|
||
}
|
||
}
|
||
|
||
/** Everyone the game is waiting for (reactions first; otherwise the current player). */
|
||
export function waiting(s: BangState): PlayerId[] {
|
||
if (s.winner) return [];
|
||
if (s.reactions.length > 0) return [...new Set(s.reactions.map(responder))];
|
||
return [s.turn.player];
|
||
}
|
||
|
||
export function validateAction(s: BangState, actor: PlayerId, a: BangAction): Validation {
|
||
const p = findPlayer(s, actor);
|
||
if (!p) return fail('이 게임의 플레이어가 아니에요.');
|
||
if (s.winner) return fail('게임이 이미 끝났어요.');
|
||
if (a.type === 'leave') return p.alive ? ok : fail('이미 게임에서 빠졌어요.');
|
||
if (!p.alive) return fail('쓰러진 사람은 행동할 수 없어요.');
|
||
const r = reactionOf(s, actor);
|
||
const why = (reason: string | null): Validation => (reason ? fail(reason) : ok);
|
||
switch (a.type) {
|
||
case 'timeout':
|
||
return waiting(s).includes(actor) ? ok : fail('시간 초과 대상이 아니에요.');
|
||
case 'pickCharacter':
|
||
if (r?.kind !== 'choose2' || !p.characterOffer) return fail('지금은 캐릭터를 고를 때가 아니에요.');
|
||
return p.characterOffer.includes(a.character) ? ok : fail('받은 캐릭터 중에서 골라 주세요.');
|
||
case 'draw': {
|
||
if (s.turn.player !== actor || s.turn.phase !== 'draw' || s.reactions.length) return fail('지금은 카드를 받을 때가 아니에요.');
|
||
if (a.jesseFrom !== undefined && a.pedroDiscard) return fail('한 가지 방법만 고를 수 있어요.');
|
||
const choice = drawChoice(s, p);
|
||
if (a.jesseFrom !== undefined) {
|
||
if (!is(p, 'jesse')) return fail('제시 존스만 다른 사람 손패에서 받을 수 있어요.');
|
||
if (!choice?.jesse.includes(a.jesseFrom)) return fail('손패가 있는 다른 사람을 골라 주세요.');
|
||
}
|
||
if (a.pedroDiscard) {
|
||
if (!is(p, 'pedro')) return fail('페드로 라미레스만 버린 카드 더미에서 받을 수 있어요.');
|
||
if (!choice?.pedro) return fail('버린 카드 더미가 비어 있어요.');
|
||
}
|
||
return ok;
|
||
}
|
||
case 'kitKeep': {
|
||
if (r?.kind !== 'kitKeep') return fail('지금은 카드를 고를 때가 아니에요.');
|
||
const [x, y] = a.keep;
|
||
if (x === y) return fail('서로 다른 카드 2장을 골라 주세요.');
|
||
return r.options.includes(x) && r.options.includes(y) ? ok : fail('보이는 카드 중에서 골라 주세요.');
|
||
}
|
||
case 'play':
|
||
return why(checkPlay(s, actor, a));
|
||
case 'respond':
|
||
if (!r || !['bang', 'indians', 'duel', 'dying'].includes(r.kind)) return fail('지금은 낼 수 있는 반응이 없어요.');
|
||
return why(checkRespond(s, p, r, a.cardIds));
|
||
case 'useBarrel':
|
||
if (r?.kind !== 'bang') return fail('뱅!을 받았을 때만 술통 판정을 해요.');
|
||
if (s.options.autoBarrel) return fail('술통 판정은 자동으로 해요.');
|
||
return barrelLeft(s, r) ? ok : fail('더 할 수 있는 술통 판정이 없어요.');
|
||
case 'takeHit':
|
||
return r && (r.kind === 'bang' || r.kind === 'indians' || r.kind === 'duel') ? ok : fail('지금은 맞을 공격이 없어요.');
|
||
case 'giveUp':
|
||
return r?.kind === 'dying' ? ok : fail('지금은 쓰러질 상황이 아니에요.');
|
||
case 'storePick':
|
||
if (r?.kind !== 'store') return fail('지금은 잡화점 카드를 고를 차례가 아니에요.');
|
||
return r.revealed.includes(a.cardId) ? ok : fail('펼쳐진 카드 중에서 골라 주세요.');
|
||
case 'sidHeal': {
|
||
if (!is(p, 'sid')) return fail('시드 케첨만 쓸 수 있는 능력이에요.');
|
||
if (!sidHealContext(s, actor)) return fail('지금은 능력을 쓸 수 없어요.');
|
||
if (p.life >= p.maxLife) return fail('생명이 이미 가득 찼어요.');
|
||
return why(distinctInHand(p, a.cardIds));
|
||
}
|
||
case 'endPlay':
|
||
return myPlayTime(s, actor) ? ok : fail('지금은 턴을 마칠 수 없어요.');
|
||
case 'discard': {
|
||
if (s.turn.player !== actor || s.turn.phase !== 'discard' || s.reactions.length) return fail('지금은 카드를 버릴 때가 아니에요.');
|
||
const need = p.hand.length - p.life;
|
||
if (a.cardIds.length !== need) return fail(`카드 ${need}장을 골라 버려 주세요.`);
|
||
return why(distinctInHand(p, a.cardIds));
|
||
}
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------- precomputed options for the view
|
||
|
||
export function playOptions(s: BangState, me: PlayerId): PlayOption[] {
|
||
if (!myPlayTime(s, me)) return [];
|
||
const p = P(s, me);
|
||
const out: PlayOption[] = [];
|
||
const others = living(s).filter((x) => x.id !== me);
|
||
for (const cardId of p.hand) {
|
||
const card = cardById(cardId);
|
||
const as: 'bang' | undefined = is(p, 'calamity') && card.kind === 'missed' ? 'bang' : undefined;
|
||
const kind = as ?? card.kind;
|
||
const base: PlayAction = { type: 'play', cardId, ...(as ? { as } : {}) };
|
||
if (!needsTarget(kind)) {
|
||
const reason = checkPlay(s, me, base);
|
||
out.push({ cardId, ...(as ? { as } : {}), ok: !reason, ...(reason ? { reason } : {}) });
|
||
continue;
|
||
}
|
||
const cands = [...others];
|
||
if ((kind === 'panic' || kind === 'catBalou') && s.options.selfTargetCatBalou && p.inPlay.length > 0) cands.push(p);
|
||
const targets: TargetOption[] = cands.map((t) => {
|
||
if (kind === 'panic' || kind === 'catBalou') {
|
||
const choices = ['hand', ...t.inPlay];
|
||
const reasons = choices.map((tc) => checkPlay(s, me, { ...base, target: t.id, targetCard: tc }));
|
||
const cards = choices.filter((_, i) => !reasons[i]);
|
||
return cards.length ? { id: t.id, ok: true, cards } : { id: t.id, ok: false, reason: reasons[0] ?? reasons.find(Boolean)! };
|
||
}
|
||
const reason = checkPlay(s, me, { ...base, target: t.id });
|
||
return reason ? { id: t.id, ok: false, reason } : { id: t.id, ok: true };
|
||
});
|
||
const any = targets.some((t) => t.ok);
|
||
const reason = any ? undefined : (targets[0]?.reason ?? '쓸 수 있는 대상이 없어요.');
|
||
out.push({ cardId, ...(as ? { as } : {}), ok: any, ...(reason ? { reason } : {}), targets });
|
||
}
|
||
return out;
|
||
}
|
||
|
||
export function promptFor(s: BangState, me: PlayerId): Prompt | null {
|
||
if (s.winner) return null;
|
||
const p = P(s, me);
|
||
if (!p.alive) return null;
|
||
const r = reactionOf(s, me);
|
||
if (r) {
|
||
switch (r.kind) {
|
||
case 'bang':
|
||
return {
|
||
kind: 'bang',
|
||
source: r.source,
|
||
via: r.via,
|
||
needed: r.needed,
|
||
options: p.hand.filter((id) => missedLike(p, id)),
|
||
canBarrel: !s.options.autoBarrel && barrelLeft(s, r),
|
||
};
|
||
case 'indians':
|
||
return { kind: 'indians', source: r.source, options: p.hand.filter((id) => bangLike(p, id)) };
|
||
case 'duel':
|
||
return { kind: 'duel', opponent: r.other, source: r.source, options: p.hand.filter((id) => bangLike(p, id)) };
|
||
case 'dying':
|
||
return { kind: 'dying', needed: 1 - p.life, beers: p.hand.filter((id) => kindOf(id) === 'beer'), beerAllowed: beerWorks(s), killer: r.killer };
|
||
case 'store':
|
||
return { kind: 'store', revealed: r.revealed.map(cardById) };
|
||
case 'kitKeep':
|
||
return { kind: 'kitKeep', options: r.options.map(cardById) };
|
||
case 'choose2':
|
||
return { kind: 'choose2', options: p.characterOffer ?? [] };
|
||
}
|
||
}
|
||
if (s.reactions.length || s.turn.player !== me) return null;
|
||
if (s.turn.phase === 'draw') {
|
||
const c = drawChoice(s, p);
|
||
const top = s.discard[s.discard.length - 1];
|
||
return { kind: 'draw', jesseTargets: c?.jesse ?? [], pedro: c?.pedro && top ? (({ id: _id, ...f }) => f)(cardById(top)) : null };
|
||
}
|
||
if (s.turn.phase === 'discard') return { kind: 'discard', count: Math.max(0, p.hand.length - p.life) };
|
||
return null;
|
||
}
|