Files
joke-app/packages/games/src/gostop/round.ts
EJClaw f5e4a7ce59 M5: 고스톱·맞고 규칙·화면·테스트
- packages/games/src/gostop: 화투 48장 + 보너스패(cards), 족보·국진·최종 공식·박·독박 정산(scoring),
  패 돌리기·바닥 정리·광팔기·총통·먹기 판정(쪽/뻑/따닥/쓸/폭탄/흔들기/보너스패)·피 뺏기·고/스톱·나가리·
  첫뻑/연뻑/삼뻑(round), validate·view(남의 손패·더미 숨김, 매칭/점수 미리 계산)·시간 초과·나가기(index).
  2인 맞고, 3인 고스톱, 4~5인 광팔기, 여러 판 세트(방 점수 제로섬).
- 테스트: 문서 §10 체크리스트 전부, 1,000 시드 무작위 진행(카드·점수 보존, onTimeout 합법),
  engine randomPlayout(누출·JSON·결정성), 정보 누출 속성 테스트.
- 화면 apps/web/src/games/gostop: 월별 바닥, 매칭 하이라이트, 두 장 중 고르기, 흔들기·폭탄·고/스톱·총통·
  국진·광팔기 선택, 먹은 패 종류별 묶음과 족보 진행, 이벤트 알림, 판 결과 계산 과정, PC·휴대폰·다크 모드.
- HwatuCard: 보너스패(2피·3피) 그림 추가. 게임 목록·레지스트리 등록, 홈 "준비 중"에서 고스톱 제거.
- E2E: 맞고 PC 방장 + 휴대폰 친구가 실제 화면 조작으로 고·스톱까지 진행.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:35:21 +09:00

745 lines
26 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** 고스톱 판 진행 (docs/games/gostop.md §4, §5): 패 돌리기, 광팔기, 총통, 먹기 판정, 피 뺏기, 고/스톱, 정산. */
import type { GameEvent, Rng } from '@bg/engine';
import { BONUS_COUNT, bestCard, cardInfo, cardValue, fullDeck, isBonus, monthOf, sameKind, type CardId } from './cards';
import { bestScore, settle } from './scoring';
import type { FloorGroup, GostopOptions, GostopRules, GostopState, PlayAction, RoundOutcome, RoundState, TurnCtx, TurnRecord } from './types';
export interface Ctx {
rng: Rng;
events: GameEvent[];
}
const REDEAL_GUARD = 50;
export function resolveRules(o: GostopOptions, players: number): GostopRules {
const matgo = players === 2;
const bonusCards = o.bonusCards === 'auto' ? (matgo ? '2+1' : 'none') : o.bonusCards;
return {
...o,
bonusCards,
nb: BONUS_COUNT[bonusCards],
winScore: o.winScore === 'auto' ? (matgo ? 7 : 3) : o.winScore,
piBakLimit: o.piBakLimit === 'auto' ? (matgo ? 7 : 5) : o.piBakLimit,
chongtongPoints: o.chongtongPoints === 'auto' ? (matgo ? 10 : 5) : o.chongtongPoints,
};
}
// ---------------------------------------------------------------- small helpers
export const floorGroup = (r: RoundState, month: number): FloorGroup | undefined => r.floor.find((g) => g.month === month);
export const floorCount = (r: RoundState, month: number): number => floorGroup(r, month)?.cards.length ?? 0;
export const handMonthCount = (r: RoundState, p: number, month: number): number => r.hands[p]!.filter((c) => !isBonus(c) && monthOf(c) === month).length;
function removeFrom(arr: CardId[], id: CardId): void {
const i = arr.indexOf(id);
if (i < 0) throw new Error(`gostop: card ${id} not found`);
arr.splice(i, 1);
}
function putOnFloor(r: RoundState, id: CardId): void {
const m = monthOf(id);
const g = floorGroup(r, m);
if (g) g.cards.push(id);
else {
r.floor.push({ month: m, cards: [id], ppeokBy: null, natural: false });
r.floor.sort((a, b) => a.month - b.month);
}
}
function takeFromFloor(r: RoundState, ids: CardId[]): void {
for (const id of ids) {
const g = floorGroup(r, monthOf(id));
if (!g) throw new Error(`gostop: floor card ${id} missing`);
removeFrom(g.cards, id);
if (g.cards.length === 0) r.floor = r.floor.filter((x) => x !== g);
}
}
function capture(r: RoundState, ctx: TurnCtx, ids: CardId[]): void {
r.captured[ctx.player]!.push(...ids);
ctx.captured.push(...ids);
}
/** Players from `start` in turn order (seat order). */
export function orderFrom(n: number, start: number): number[] {
return Array.from({ length: n }, (_, i) => (start + i) % n);
}
export function currentScore(s: GostopState, p: number): number {
return bestScore(s.round!.captured[p]!, s.rules).calc.total;
}
export function hasChongtong(r: RoundState, p: number): number[] {
const out: number[] = [];
for (let m = 1; m <= 12; m++) if (handMonthCount(r, p, m) === 4) out.push(m);
return out;
}
// ---------------------------------------------------------------- dealing
function emptyRound(s: GostopState): RoundState {
const n = s.players.length;
const arr = <T>(f: () => T): T[] => Array.from({ length: n }, f);
const rules = s.rules;
return {
no: s.roundNo,
participants: [],
sellOrder: [],
sellCursor: 0,
sellDecisions: [],
sellers: [],
hands: arr(() => []),
bombDummies: arr(() => 0),
revealed: arr(() => []),
shakenMonths: arr(() => []),
deck: [],
floor: [],
captured: arr(() => []),
gukjinChoice: arr(() => null),
goCount: arr(() => 0),
lastGoScore: arr(() => 0),
goOrder: [],
shakes: arr(() => 0),
bombs: arr(() => 0),
ppeokCount: arr(() => 0),
ppeokTurns: arr(() => []),
turnsTaken: arr(() => 0),
turn: s.dealer,
step: 'play',
pending: null,
stopBy: null,
chongtongBy: null,
nagariMult: rules.nagariMultiplier === 'x2' ? Math.min(2 ** s.nagariStreak, rules.nagariMaxMultiplier) : 1,
instant: arr(() => 0),
turnSeq: 0,
lastTurn: null,
outcome: null,
redeals: 0,
};
}
/**
* Shuffles and deals to `who` (§4.3), then cleans the floor (§4.4): floor bonus cards go to the dealer
* with a refill from the deck; four of a month on the floor → shuffle again.
*/
function deal(s: GostopState, r: RoundState, who: number[], ctx: Ctx): void {
const rules = s.rules;
const handSize = s.mode === 'matgo' ? 10 : 7;
const floorSize = s.mode === 'matgo' ? 8 : 6;
for (let guard = 0; ; guard++) {
const deck = ctx.rng.shuffle(fullDeck(rules.nb));
for (const p of who) r.hands[p] = deck.splice(0, handSize);
const floor = deck.splice(0, floorSize);
const taken: CardId[] = [];
for (let i = 0; i < floor.length; i++) {
while (isBonus(floor[i]!)) {
taken.push(floor[i]!);
floor[i] = deck.shift()!;
}
}
const counts = new Map<number, number>();
for (const c of floor) counts.set(monthOf(c), (counts.get(monthOf(c)) ?? 0) + 1);
if ([...counts.values()].some((v) => v === 4) && guard < REDEAL_GUARD) {
r.redeals++;
ctx.events.push({ type: 'redeal', reason: 'floorFour' });
continue;
}
r.deck = deck;
r.captured = r.captured.map(() => []);
r.captured[s.dealer] = taken;
r.floor = [];
for (const c of floor) putOnFloor(r, c);
for (const g of r.floor) if (g.cards.length === 3) g.natural = true;
ctx.events.push({ type: 'dealt', players: who.map((p) => s.players[p]), handSize, floor: [...floor] });
if (taken.length) ctx.events.push({ type: 'bonusTaken', player: s.players[s.dealer], cards: taken });
return;
}
}
export function startRound(s: GostopState, ctx: Ctx): void {
s.roundNo += 1;
s.phase = 'playing';
s.ready = [];
const r = emptyRound(s);
s.round = r;
const n = s.players.length;
const order = orderFrom(n, s.dealer);
ctx.events.push({ type: 'roundStart', roundNo: s.roundNo, dealer: s.players[s.dealer], nagariMult: r.nagariMult });
deal(s, r, order, ctx);
if (n >= 4) {
r.step = 'sell';
r.sellOrder = order.slice(1);
r.sellCursor = 0;
progressSell(s, ctx);
} else {
r.participants = order;
afterDeal(s, ctx);
}
}
// ---------------------------------------------------------------- 광팔기 (§5.8)
export function sellableCards(s: GostopState, p: number): CardId[] {
const r = s.round!;
return r.hands[p]!.filter((c) => {
const i = cardInfo(c, s.rules.nb);
if (i.kind === 'gwang') return true;
return s.rules.gwangSellCards === 'gwangPlus' && (i.gukjin || i.bonus || (i.kind === 'pi' && i.piValue === 2));
}).sort((a, b) => a - b);
}
/** Who must decide next, or null when the remaining decisions are automatic. */
export function sellDecider(s: GostopState): number | null {
const r = s.round!;
if (r.step !== 'sell' || r.sellCursor >= r.sellOrder.length) return null;
const n = s.players.length;
const plays = 1 + r.sellDecisions.filter((d) => !d.sell).length;
const dies = r.sellDecisions.filter((d) => d.sell).length;
if (plays >= 3 || dies >= n - 3) return null;
return r.sellOrder[r.sellCursor]!;
}
export function decideSell(s: GostopState, p: number, sell: boolean, ctx: Ctx): void {
const r = s.round!;
r.sellDecisions.push({ idx: p, sell, auto: false });
r.sellCursor++;
ctx.events.push({ type: sell ? 'sellDie' : 'sellPlay', player: s.players[p] });
progressSell(s, ctx);
}
function progressSell(s: GostopState, ctx: Ctx): void {
const r = s.round!;
const n = s.players.length;
while (r.sellCursor < r.sellOrder.length) {
const plays = 1 + r.sellDecisions.filter((d) => !d.sell).length;
const dies = r.sellDecisions.filter((d) => d.sell).length;
if (plays < 3 && dies < n - 3) return; // a real decision is needed
const p = r.sellOrder[r.sellCursor]!;
r.sellDecisions.push({ idx: p, sell: plays >= 3, auto: true });
r.sellCursor++;
}
finishSelling(s, ctx);
}
function finishSelling(s: GostopState, ctx: Ctx): void {
const r = s.round!;
const rules = s.rules;
const order = orderFrom(s.players.length, s.dealer);
const dying = new Set(r.sellDecisions.filter((d) => d.sell).map((d) => d.idx));
r.participants = order.filter((p) => !dying.has(p));
const payers = rules.gwangPayer === 'nonDealerPlayers' ? r.participants.slice(1) : r.participants;
const back: CardId[] = [];
for (const p of order) {
if (!dying.has(p)) continue;
const shown = sellableCards(s, p);
const each = shown.length * rules.gwangPrice;
for (const q of payers) {
s.totals[q]! -= each;
r.instant[q]! -= each;
}
s.totals[p]! += each * payers.length;
r.instant[p]! += each * payers.length;
s.stats.gwangSold[p]! += shown.length;
r.sellers.push({ idx: p, shown, paid: each * payers.length });
ctx.events.push({ type: 'gwangSold', player: s.players[p], cards: shown, points: each * payers.length });
back.push(...r.hands[p]!);
r.hands[p] = [];
}
r.deck = ctx.rng.shuffle([...r.deck, ...back]);
afterDeal(s, ctx);
}
// ---------------------------------------------------------------- 총통 (§5.7)
function afterDeal(s: GostopState, ctx: Ctx): void {
const r = s.round!;
for (let guard = 0; guard <= REDEAL_GUARD; guard++) {
const holder = s.rules.chongtong === 'off' ? undefined : r.participants.find((p) => hasChongtong(r, p).length > 0);
if (holder === undefined) break;
if (s.rules.chongtong === 'win') {
r.step = 'chongtong';
r.chongtongBy = holder;
r.turn = holder;
return;
}
if (guard === REDEAL_GUARD) break;
r.redeals++;
ctx.events.push({ type: 'redeal', reason: 'chongtong' });
deal(s, r, r.participants, ctx);
}
startPlay(s);
}
function startPlay(s: GostopState): void {
const r = s.round!;
r.step = 'play';
r.chongtongBy = null;
r.turn = r.participants[0]!;
}
export function decideChongtong(s: GostopState, p: number, declare: boolean, ctx: Ctx): void {
const r = s.round!;
if (!declare) {
ctx.events.push({ type: 'chongtongSkip', player: s.players[p] });
startPlay(s);
return;
}
const months = hasChongtong(r, p);
const shown = r.hands[p]!.filter((c) => !isBonus(c) && monthOf(c) === months[0]).sort((a, b) => a - b);
r.revealed[p]!.push(...shown);
ctx.events.push({ type: 'chongtong', player: s.players[p], cards: shown });
instantWin(s, p, 'chongtong', shown, ctx);
}
/** 총통·삼뻑: points × 나가리 배수 from every opponent, no 박 (§5.7, §5.11). */
function instantWin(s: GostopState, p: number, type: 'chongtong' | 'samppeok', shown: CardId[], ctx: Ctx): void {
const r = s.round!;
const amount = s.rules.chongtongPoints * r.nagariMult;
const outcome: RoundOutcome = {
type,
winner: p,
baseScore: s.rules.chongtongPoints,
breakdown: [{ name: type === 'chongtong' ? '총통' : '삼뻑', points: s.rules.chongtongPoints }],
goCount: 0,
multipliers: r.nagariMult > 1 ? [{ name: '나가리 배수', factor: r.nagariMult }] : [],
perLoser: amount,
payments: r.participants.filter((q) => q !== p).map((q) => ({ from: q, amount, baks: [] })),
gukjinAs: null,
shown,
};
endRound(s, outcome, ctx);
}
// ---------------------------------------------------------------- a turn (§5.1–5.6)
/** Two floor cards that differ → the player must pick (§5.2). */
export function needsTarget(s: GostopState, month: number): boolean {
const g = floorGroup(s.round!, month);
return !!g && g.cards.length === 2 && !sameKind(g.cards[0]!, g.cards[1]!, s.rules.nb);
}
function flip(s: GostopState, ctx: TurnCtx): CardId {
const r = s.round!;
for (;;) {
const c = r.deck.shift();
if (c === undefined) throw new Error('gostop: deck exhausted');
ctx.flipped.push(c);
if (!isBonus(c)) return c;
capture(r, ctx, [c]);
ctx.tags.push('bonusFlip');
}
}
function pileSteal(s: GostopState, g: FloorGroup, ctx: TurnCtx): void {
if (g.ppeokBy === ctx.player) {
ctx.steal += s.rules.jaPpeokSteal;
ctx.tags.push('jaPpeok');
} else if (g.ppeokBy !== null) {
ctx.steal += 1;
ctx.tags.push('ppeokEat');
} else if (g.natural) {
if (s.rules.naturalThreeSteal) ctx.steal += 1;
ctx.tags.push('ppeokEat');
}
}
const sweepCounts = (s: GostopState, ctx: TurnCtx): boolean => !ctx.lastOfRound || s.rules.lastTurnSweepBonus;
export function playCard(s: GostopState, p: number, a: PlayAction, ctx: Ctx): void {
const r = s.round!;
const nb = s.rules.nb;
const t: TurnCtx = { player: p, played: [], flipped: [], captured: [], tags: [], steal: 0, lastOfRound: false };
// 보너스패: goes to my pile, I take the deck top and play again in the same turn (§5.6).
if (a.card !== 'dummy' && isBonus(a.card)) {
removeFrom(r.hands[p]!, a.card);
capture(r, t, [a.card]);
t.played.push(a.card);
t.tags.push('bonus');
const drawn = r.deck.shift();
if (drawn === undefined) throw new Error('gostop: deck exhausted (bonus draw)');
r.hands[p]!.push(drawn);
ctx.events.push({ type: 'bonusPlayed', player: s.players[p], card: a.card });
record(s, t, ctx);
return;
}
let H: CardId | null = null;
let m1 = 0;
let k = 0;
if (a.card === 'dummy') {
r.bombDummies[p]! -= 1;
t.tags.push('dummy');
ctx.events.push({ type: 'dummyPlayed', player: s.players[p] });
} else if (a.bomb) {
const m = monthOf(a.card);
const mine = r.hands[p]!.filter((c) => !isBonus(c) && monthOf(c) === m).sort((x, y) => x - y);
for (const c of mine) removeFrom(r.hands[p]!, c);
r.revealed[p] = r.revealed[p]!.filter((c) => !mine.includes(c));
const g = floorGroup(r, m)!;
const floorCards = [...g.cards];
takeFromFloor(r, floorCards);
t.played.push(...mine);
capture(r, t, [...mine, ...floorCards]);
t.steal += 1;
t.tags.push('bomb');
r.bombs[p]! += 1;
r.bombDummies[p]! += 2;
ctx.events.push({ type: 'bomb', player: s.players[p], cards: mine });
} else {
H = a.card;
m1 = monthOf(H);
k = floorCount(r, m1);
removeFrom(r.hands[p]!, H);
r.revealed[p] = r.revealed[p]!.filter((c) => c !== H);
t.played.push(H);
if (a.shake) {
const rest = r.hands[p]!.filter((c) => !isBonus(c) && monthOf(c) === m1);
r.shakes[p]! += 1;
r.shakenMonths[p]!.push(m1);
for (const c of rest) if (!r.revealed[p]!.includes(c)) r.revealed[p]!.push(c);
t.tags.push('shake');
ctx.events.push({ type: 'shake', player: s.players[p], cards: [H, ...rest].sort((x, y) => x - y) });
}
ctx.events.push({ type: 'played', player: s.players[p], card: H });
}
const F = flip(s, t);
t.lastOfRound = r.deck.length === 0;
ctx.events.push({ type: 'flipped', player: s.players[p], cards: [...t.flipped] });
if (H !== null) {
const g = floorGroup(r, m1);
if (monthOf(F) === m1) {
if (k === 0) {
capture(r, t, [H, F]);
t.tags.push('jjok');
if (sweepCounts(s, t)) t.steal += 1;
} else if (k === 1) {
g!.cards.push(H, F);
g!.ppeokBy = p;
g!.natural = false;
r.ppeokCount[p]! += 1;
r.ppeokTurns[p]!.push(r.turnsTaken[p]!);
t.tags.push('ppeok');
} else {
// k = 2 → 따닥 (k = 3 is impossible: the 4th card of the month was H).
const cards = [...g!.cards];
takeFromFloor(r, cards);
capture(r, t, [...cards, H, F]);
t.tags.push('ttadak');
t.steal += 1;
}
finishTurn(s, t, ctx);
return;
}
if (k === 0) putOnFloor(r, H);
else if (k === 1) {
const c = g!.cards[0]!;
takeFromFloor(r, [c]);
capture(r, t, [H, c]);
} else if (k === 2) {
const target = a.target ?? bestCard(g!.cards, nb);
takeFromFloor(r, [target]);
capture(r, t, [H, target]);
} else {
const cards = [...g!.cards];
pileSteal(s, g!, t);
takeFromFloor(r, cards);
capture(r, t, [...cards, H]);
}
}
resolveFlip(s, F, t, ctx);
}
/** F 처리 (§5.2): j = floor cards of F's month. */
function resolveFlip(s: GostopState, F: CardId, t: TurnCtx, ctx: Ctx): void {
const r = s.round!;
const nb = s.rules.nb;
const g = floorGroup(r, monthOf(F));
const j = g?.cards.length ?? 0;
if (j === 0) putOnFloor(r, F);
else if (j === 1) {
const c = g!.cards[0]!;
takeFromFloor(r, [c]);
capture(r, t, [F, c]);
} else if (j === 2) {
if (sameKind(g!.cards[0]!, g!.cards[1]!, nb)) {
const c = bestCard(g!.cards, nb);
takeFromFloor(r, [c]);
capture(r, t, [F, c]);
} else {
r.pending = { flipped: F, options: [...g!.cards].sort((a, b) => a - b), ctx: t };
r.step = 'chooseFlip';
return;
}
} else {
const cards = [...g!.cards];
pileSteal(s, g!, t);
takeFromFloor(r, cards);
capture(r, t, [...cards, F]);
}
finishTurn(s, t, ctx);
}
export function chooseFlip(s: GostopState, target: CardId, ctx: Ctx): void {
const r = s.round!;
const pend = r.pending!;
r.pending = null;
r.step = 'play';
takeFromFloor(r, [target]);
capture(r, pend.ctx, [pend.flipped, target]);
finishTurn(s, pend.ctx, ctx);
}
/** Gives `n` 피 per opponent, lowest value first (일반 피 → 쌍피·2피 → 3피), then lowest id (§5.3). */
function steal(s: GostopState, t: TurnCtx): [number, CardId[]][] {
const r = s.round!;
const nb = s.rules.nb;
const out: [number, CardId[]][] = [];
for (const q of r.participants) {
if (q === t.player) continue;
const pis = r.captured[q]!.filter((c) => cardInfo(c, nb).kind === 'pi').sort((a, b) => cardInfo(a, nb).piValue - cardInfo(b, nb).piValue || a - b);
const given = pis.slice(0, t.steal);
for (const c of given) removeFrom(r.captured[q]!, c);
r.captured[t.player]!.push(...given);
if (given.length) out.push([q, given]);
}
return out;
}
function record(s: GostopState, t: TurnCtx, ctx: Ctx, stolen: [number, CardId[]][] = [], bonusPoints = 0): TurnRecord {
const r = s.round!;
r.turnSeq += 1;
const rec: TurnRecord = { seq: r.turnSeq, player: t.player, played: t.played, flipped: t.flipped, captured: t.captured, tags: [...t.tags], stolen, bonusPoints };
r.lastTurn = rec;
return rec;
}
function finishTurn(s: GostopState, t: TurnCtx, ctx: Ctx): void {
const r = s.round!;
const p = t.player;
const others = r.participants.filter((q) => q !== p);
if (r.floor.length === 0) {
t.tags.push('sseul');
if (sweepCounts(s, t)) t.steal += 1;
}
const stolen = t.steal > 0 ? steal(s, t) : [];
const turnIdx = r.turnsTaken[p]!;
r.turnsTaken[p]! += 1;
// 첫뻑·연뻑·삼뻑 (§5.11)
let bonusPoints = 0;
let samppeok = false;
if (t.tags.includes('ppeok') && s.rules.ppeokBonus) {
if (r.ppeokCount[p]! >= 3) {
samppeok = true;
t.tags.push('samPpeok');
} else if (turnIdx === 0) {
bonusPoints = 3;
t.tags.push('firstPpeok');
} else if (turnIdx === 1 && r.ppeokTurns[p]!.includes(0)) {
bonusPoints = 6;
t.tags.push('yeonPpeok');
}
for (const q of others) {
s.totals[q]! -= bonusPoints;
r.instant[q]! -= bonusPoints;
s.totals[p]! += bonusPoints;
r.instant[p]! += bonusPoints;
}
}
for (const tag of t.tags) if (!['bonus', 'bonusFlip', 'dummy', 'bomb', 'shake'].includes(tag)) ctx.events.push({ type: tag, player: s.players[p] });
if (stolen.length) ctx.events.push({ type: 'piStolen', player: s.players[p], from: stolen.map(([q, cs]) => ({ player: s.players[q], cards: cs })) });
record(s, t, ctx, stolen, bonusPoints);
if (samppeok) {
instantWin(s, p, 'samppeok', [], ctx);
return;
}
const score = currentScore(s, p);
ctx.events.push({ type: 'scoreUpdate', player: s.players[p], score });
if (score >= s.rules.winScore && (r.goCount[p] === 0 || score > r.lastGoScore[p]!)) {
if (r.hands[p]!.length === 0) {
ctx.events.push({ type: 'stop', player: s.players[p], auto: true });
stop(s, p, ctx);
} else {
r.step = 'goStop';
r.turn = p;
ctx.events.push({ type: 'goStopPrompt', player: s.players[p], score });
}
return;
}
advance(s, p, ctx);
}
/** Next player with something to play; nobody left → 나가리 (§5.10). */
function advance(s: GostopState, from: number, ctx: Ctx): void {
const r = s.round!;
const parts = r.participants;
const i = parts.indexOf(from);
for (let step = 1; step <= parts.length; step++) {
const q = parts[(i + step) % parts.length]!;
if (r.hands[q]!.length > 0 || r.bombDummies[q]! > 0) {
r.step = 'play';
r.turn = q;
return;
}
}
if (r.deck.length !== 0) throw new Error('gostop: hands empty but deck not empty');
ctx.events.push({ type: 'nagari' });
endRound(
s,
{ type: 'nagari', winner: null, baseScore: 0, breakdown: [], goCount: 0, multipliers: [], perLoser: 0, payments: [], gukjinAs: null, shown: [] },
ctx,
);
}
export function decideGoStop(s: GostopState, p: number, decision: 'go' | 'stop', ctx: Ctx): void {
const r = s.round!;
if (decision === 'stop') {
ctx.events.push({ type: 'stop', player: s.players[p], auto: false });
stop(s, p, ctx);
return;
}
r.goCount[p]! += 1;
r.lastGoScore[p] = currentScore(s, p);
r.goOrder.push(p);
s.stats.goCalls[p]! += 1;
ctx.events.push({ type: 'go', player: s.players[p], count: r.goCount[p] });
advance(s, p, ctx);
}
/** The 국진 owner who still has to choose (ask mode) before settling. */
export function gukjinPending(s: GostopState): number | null {
const r = s.round!;
if (s.rules.gukjinMode !== 'ask') return null;
const holder = r.participants.find((q) => r.captured[q]!.includes(32));
return holder !== undefined && r.gukjinChoice[holder] === null ? holder : null;
}
function stop(s: GostopState, p: number, ctx: Ctx): void {
const r = s.round!;
r.stopBy = p;
if (gukjinPending(s) !== null) {
r.step = 'gukjin';
r.turn = gukjinPending(s)!;
return;
}
settleStop(s, ctx);
}
export function settleInput(s: GostopState, winner: number) {
const r = s.round!;
return {
rules: s.rules,
mode: s.mode,
winner,
participants: r.participants,
captured: r.captured,
goCount: r.goCount,
goOrder: r.goOrder,
shakes: r.shakes,
bombs: r.bombs,
nagariMult: r.nagariMult,
gukjinChoice: r.gukjinChoice,
};
}
export function decideGukjin(s: GostopState, p: number, as: 'yeol' | 'pi', ctx: Ctx): void {
const r = s.round!;
r.gukjinChoice[p] = as;
ctx.events.push({ type: 'gukjin', player: s.players[p], as });
settleStop(s, ctx);
}
/** The automatic 국진 rule for the pending owner (timeout in ask mode). */
export function autoGukjin(s: GostopState): 'yeol' | 'pi' {
return settle(settleInput(s, s.round!.stopBy!)).gukjinAs ?? 'yeol';
}
function settleStop(s: GostopState, ctx: Ctx): void {
const r = s.round!;
const st = settle(settleInput(s, r.stopBy!));
const { calcs: _c, ...rest } = st;
endRound(s, { type: 'stop', ...rest, shown: [] }, ctx);
}
// ---------------------------------------------------------------- round end
function endRound(s: GostopState, outcome: RoundOutcome, ctx: Ctx): void {
const r = s.round!;
r.outcome = outcome;
r.step = 'done';
r.pending = null;
const delta = [...r.instant];
if (outcome.winner !== null) {
for (const pay of outcome.payments) {
s.totals[pay.from]! -= pay.amount;
s.totals[outcome.winner]! += pay.amount;
delta[pay.from]! -= pay.amount;
delta[outcome.winner]! += pay.amount;
if (pay.baks.includes('pi')) s.stats.piBakGiven[outcome.winner]! += 1;
}
s.stats.wins[outcome.winner]! += 1;
s.nagariStreak = 0;
s.dealer = outcome.winner;
} else {
s.stats.nagari += 1;
s.nagariStreak += 1;
}
const amount = outcome.payments.reduce((a, x) => a + x.amount, 0);
s.log.push({
no: s.roundNo,
type: outcome.type,
winner: outcome.winner,
amount,
delta,
breakdown: [...outcome.breakdown.map((b) => `${b.name} ${b.points}점`), ...outcome.multipliers.map((m) => `${m.name} x${m.factor}`)],
});
ctx.events.push({ type: 'roundEnded', roundNo: s.roundNo, outcome: outcome.type, winner: outcome.winner === null ? null : s.players[outcome.winner], amount });
if (s.roundNo >= s.rules.rounds) finishGame(s, ctx);
else {
s.phase = 'roundResult';
s.ready = [];
}
}
function finishGame(s: GostopState, ctx: Ctx): void {
s.phase = 'finished';
const ids = s.players.map((_, i) => i).sort((a, b) => s.totals[b]! - s.totals[a]! || a - b);
const ranking: string[][] = [];
let last: number | null = null;
for (const i of ids) {
if (last !== null && s.totals[i] === last) ranking[ranking.length - 1]!.push(s.players[i]!);
else ranking.push([s.players[i]!]);
last = s.totals[i]!;
}
const scores = Object.fromEntries(s.players.map((p, i) => [p, s.totals[i]!]));
const top = s.totals[ids[0]!]!;
const tie = ranking[0]!.length > 1 ? ` (공동 ${ranking[0]!.length}명)` : '';
const nag = s.stats.nagari ? `, 나가리 ${s.stats.nagari}번` : '';
const summary = `${s.roundNo}판 끝${nag}. 1위 ${top >= 0 ? '+' : ''}${top.toLocaleString('ko-KR')}점${tie}`;
s.final = { ranking, scores, summary };
ctx.events.push({ type: 'setEnded', ranking });
}
// ---------------------------------------------------------------- automatic play (§8.5)
/** Deterministic play for timeouts: 빈패 → 보너스패 → 가장 값진 바닥 패를 먹는 패 → 가장 싼 패. */
export function autoPlay(s: GostopState, p: number): PlayAction {
const r = s.round!;
const nb = s.rules.nb;
if (r.bombDummies[p]! > 0) return { type: 'play', card: 'dummy' };
const hand = [...r.hands[p]!].sort((a, b) => a - b);
const bonus = hand.find(isBonus);
if (bonus !== undefined) return { type: 'play', card: bonus };
let best: { card: CardId; value: number } | null = null;
for (const c of hand) {
const g = floorGroup(r, monthOf(c));
if (!g) continue;
const value = Math.max(...g.cards.map((x) => cardValue(x, nb)));
if (!best || value > best.value) best = { card: c, value };
}
if (best) {
const g = floorGroup(r, monthOf(best.card))!;
return g.cards.length === 2 && needsTarget(s, g.month) ? { type: 'play', card: best.card, target: bestCard(g.cards, nb) } : { type: 'play', card: best.card };
}
const cheapest = [...hand].sort((a, b) => cardValue(a, nb) - cardValue(b, nb) || a - b)[0]!;
return { type: 'play', card: cheapest };
}