다빈치 코드 조커 숨김·공개 타일 표시, 바퀴벌레 포커 내 빠른 말 표시, 난수를 ChaCha20으로
- 다빈치 코드: 조커를 놓는 단계(placeJoker)를 상대·관전자 화면에는 바로 전 단계로 보여 줌(서버 view) - 다빈치 코드: 공개된 타일은 반 칸 위로 올리고 아래에 노란 줄, 숨은 타일은 제자리 - 바퀴벌레 포커: 내가 한 빠른 말도 내 자리 위 말풍선으로 표시 - 난수: 새 게임은 256비트 OS 시드 + ChaCha20(RFC 8439, 암호학적 생성기). 옛 게임(128비트)은 sfc32 그대로라 다시 보기 동일 - 테스트: RFC 테스트 벡터, 균등성(카이제곱), 상태 이어받기, 조커 단계 비공개 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -84,7 +84,7 @@ describe('M1 integration scenarios', () => {
|
||||
const stats = await api(s.base, '/api/me/stats', { cookie: a.cookie });
|
||||
expect(stats.body.stats).toEqual([{ gameId: 'omok', played: 1, wins: 1, draws: 0 }]);
|
||||
const room2 = (await a.next('room', (m) => m.room.status === 'finished').catch(() => a.lastOf('room')!)).room;
|
||||
expect(room2.lastSeed).toMatch(/^[0-9a-f]{32}$/);
|
||||
expect(room2.lastSeed).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(room2.sessionStats[a.id]).toEqual({ played: 1, wins: 1 });
|
||||
});
|
||||
|
||||
|
||||
@@ -295,8 +295,10 @@ const CSS = `
|
||||
.cp-true:hover:not(:disabled), .cp-false:hover:not(:disabled) { filter: brightness(1.08); }
|
||||
.cp-peek { min-height: 56px; }
|
||||
.cp-why { font-size: .85rem; color: var(--text-sub); }
|
||||
.cp-me { background: var(--surface); border-radius: var(--radius-lg); box-shadow: var(--shadow); padding: 10px 12px; border: 3px solid var(--primary); display: flex; flex-direction: column; gap: 8px; }
|
||||
.cp-me { position: relative; background: var(--surface); border-radius: var(--radius-lg); box-shadow: var(--shadow); padding: 10px 12px; border: 3px solid var(--primary); display: flex; flex-direction: column; gap: 8px; }
|
||||
.cp-me.turn { border-color: var(--focus); }
|
||||
/* My own 빠른 말: next to my name (the timer sits on the right). */
|
||||
.cp-me > .cp-bubble { right: auto; left: 16px; top: -16px; }
|
||||
.cp-me-row { display: flex; gap: 14px; flex-wrap: wrap; align-items: flex-start; }
|
||||
.cp-me-row > div { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
|
||||
.cp-help { font-size: .85rem; color: var(--text-sub); }
|
||||
@@ -683,12 +685,32 @@ function WaitPanel({ v, players, me }: { v: CockroachView; players: Record<strin
|
||||
);
|
||||
}
|
||||
|
||||
function MyArea({ v, me, players, deadline, offering }: { v: CockroachView; me: string; players: Record<string, PublicUser>; deadline: number | null; offering: boolean }) {
|
||||
function MyArea({
|
||||
v,
|
||||
me,
|
||||
players,
|
||||
deadline,
|
||||
offering,
|
||||
bubble,
|
||||
}: {
|
||||
v: CockroachView;
|
||||
me: string;
|
||||
players: Record<string, PublicUser>;
|
||||
deadline: number | null;
|
||||
offering: boolean;
|
||||
/** What I just said with 빠른 말: shown over my own area too, like everybody else's. */
|
||||
bubble: string | null;
|
||||
}) {
|
||||
const front = v.fronts[me]!;
|
||||
const active = waitingOn(v) === me;
|
||||
const total = v.handCounts[me] ?? 0;
|
||||
return (
|
||||
<section className={`cp-me${active ? ' turn' : ''}`} aria-label="내 자리">
|
||||
{bubble && (
|
||||
<span className="cp-bubble" aria-hidden>
|
||||
{bubble}
|
||||
</span>
|
||||
)}
|
||||
<div className="cp-head">
|
||||
<Avatar user={userOf(players, me)} size={26} />
|
||||
<span className="cp-name">{nick(players, me)} (나)</span>
|
||||
@@ -792,12 +814,7 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
<WaitPanel v={v} players={players} me={me} />
|
||||
)}
|
||||
</div>
|
||||
{amPlayer && <MyArea v={v} me={me!} players={players} deadline={deadline} offering={offering} />}
|
||||
{amPlayer && bubbles[me!] && (
|
||||
<span className="sr-only" aria-hidden>
|
||||
{bubbles[me!]}
|
||||
</span>
|
||||
)}
|
||||
{amPlayer && <MyArea v={v} me={me!} players={players} deadline={deadline} offering={offering} bubble={bubbles[me!] ?? null} />}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
|
||||
@@ -34,7 +34,7 @@ export function helpNow(v: DavinciView, me: string | null, players: Record<strin
|
||||
draw: '타일을 가져오는 중이에요',
|
||||
guess: '추리하는 중이에요',
|
||||
afterCorrect: '맞혀서 계속할지 고르는 중이에요',
|
||||
placeJoker: '조커를 넣을 자리를 고르는 중이에요',
|
||||
placeJoker: '타일을 놓는 중이에요', // never shown: the server hides this phase from the others
|
||||
revealOwn: '틀려서 자기 타일을 공개하는 중이에요',
|
||||
};
|
||||
return `${curNick}이 ${doing[v.phase] ?? '차례를 진행하는 중이에요'}. 기다려 주세요.\n내 숨은 타일은 ${hidden(v, me!)}개 남았어요. 공개된 숫자와 위치, 추리 기록을 보며 상대 숫자를 짐작해 보세요.`;
|
||||
|
||||
@@ -57,7 +57,8 @@ const CSS = `
|
||||
.dv-badge.turn { background: var(--focus); color: #1c1e21; }
|
||||
.dv-badge.out { background: var(--danger-soft); color: var(--danger); }
|
||||
.dv-badge.ok { background: var(--success-soft); color: var(--success); }
|
||||
.dv-row { display: flex; flex-wrap: wrap; gap: 6px; align-items: flex-end; padding-top: 8px; }
|
||||
.dv-row { --lift: 34px; display: flex; flex-wrap: wrap; gap: 6px; align-items: flex-end; padding-top: calc(8px + var(--lift)); }
|
||||
.dv-me .dv-row { --lift: 40px; }
|
||||
.dv-slot { display: flex; flex-direction: column; align-items: center; gap: 2px; }
|
||||
.dv-pos { font-size: .75rem; color: var(--text-sub); font-variant-numeric: tabular-nums; line-height: 1; }
|
||||
.dv-tile { --w: 46px; width: var(--w); height: calc(var(--w) * 1.42); border-radius: 8px; display: flex; align-items: center; justify-content: center;
|
||||
@@ -68,7 +69,8 @@ const CSS = `
|
||||
.dv-tile.back.black { background: repeating-linear-gradient(45deg, #2a2c33 0 5px, #1b1c21 5px 10px); }
|
||||
.dv-tile.back.white { background: repeating-linear-gradient(45deg, #fbf9f4 0 5px, #e6e1d6 5px 10px); }
|
||||
.dv-tile .q { opacity: .45; font-size: .62em; }
|
||||
.dv-tile.open::after { content: ''; position: absolute; left: 18%; right: 18%; bottom: 4px; height: 4px; border-radius: 2px; background: #f59e0b; }
|
||||
.dv-slot.open > .dv-pick { position: relative; top: calc(-1 * var(--lift)); }
|
||||
.dv-slot.open > .dv-pick::after { content: ''; position: absolute; left: 12%; right: 12%; bottom: -7px; height: 5px; border-radius: 3px; background: #f59e0b; }
|
||||
.dv-tile.secret { outline: 3px dashed var(--primary); outline-offset: 2px; }
|
||||
.dv-tile.sm { --w: 30px; }
|
||||
.dv-tile.lg { --w: 54px; }
|
||||
@@ -128,7 +130,8 @@ const CSS = `
|
||||
@media (max-width: 719px) {
|
||||
.dv-tile { --w: 34px; border-radius: 6px; }
|
||||
.dv-tile.lg { --w: 37px; }
|
||||
.dv-row { gap: 4px; }
|
||||
.dv-row { gap: 4px; --lift: 26px; }
|
||||
.dv-me .dv-row { --lift: 28px; }
|
||||
.dv-mid { grid-template-columns: minmax(0, 1fr); }
|
||||
.dv-board { max-height: none; overflow: visible; }
|
||||
}
|
||||
@@ -308,7 +311,7 @@ function PlayerRow({
|
||||
const can = canPick && !t.revealed;
|
||||
const selected = sel?.target === id && sel.index === i;
|
||||
return (
|
||||
<div className="dv-slot" key={i}>
|
||||
<div className={`dv-slot${t.revealed ? ' open' : ''}`} key={i}>
|
||||
<button
|
||||
type="button"
|
||||
className={`dv-pick${can ? ' can' : ''}${selected ? ' sel' : ''}`}
|
||||
@@ -368,7 +371,7 @@ function MyRow({
|
||||
const can = revealing && !t.revealed;
|
||||
return [
|
||||
gap(i),
|
||||
<div className="dv-slot" key={i}>
|
||||
<div className={`dv-slot${t.revealed ? ' open' : ''}`} key={i}>
|
||||
{can ? (
|
||||
<button type="button" className="dv-pick can" aria-label={`내 ${tileLabel(t, i, true)}, 눌러서 공개`} onClick={() => act({ type: 'revealOwn', index: i })}>
|
||||
<Tile color={t.color} n={t.n} revealed={t.revealed} mine size="lg" fx={fx.get(`${me}:${i}`)} />
|
||||
@@ -392,7 +395,7 @@ function MyRow({
|
||||
<span className="dv-mini white" style={{ outline: '2px dashed var(--primary)', outlineOffset: 1 }} /> 점선: 상대에게 숨김
|
||||
</span>
|
||||
<span>
|
||||
<span className="dv-mini white" style={{ boxShadow: 'inset 0 -4px 0 #f59e0b' }} /> 아래 노란 줄: 모두에게 공개됨
|
||||
<span className="dv-mini white" style={{ boxShadow: 'inset 0 -4px 0 #f59e0b' }} /> 반 칸 위 + 아래 노란 줄: 모두에게 공개됨
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
@@ -510,7 +513,7 @@ function ActionPanel({
|
||||
draw: '타일을 가져오는 중이에요',
|
||||
guess: '추리하는 중이에요',
|
||||
afterCorrect: '맞혔어요! 계속할지 고르는 중이에요',
|
||||
placeJoker: '조커를 넣을 자리를 고르는 중이에요',
|
||||
placeJoker: '타일을 놓는 중이에요', // never shown: the server hides this phase from the others
|
||||
revealOwn: '틀려서 자기 타일을 공개하는 중이에요',
|
||||
finished: '',
|
||||
};
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
## 5. 숨겨진 정보와 공정성
|
||||
- 클라이언트에는 `view(state, viewer)` 결과만 보낸다. 덱 순서, 남의 패, 마피아 직업, RNG 시드는 절대 보내지 않는다.
|
||||
- 게임마다 "정보 유출 테스트": 무작위 대국을 돌리며 매 순간 플레이어 A의 view(JSON 문자열)에 다른 사람만 알아야 하는 값(카드 ID 등)이 들어 있지 않은지 검사.
|
||||
- 셔플: 게임 시작 시 `crypto.getRandomValues`로 128비트 시드를 만들고, 상태 안의 시드 PRNG(sfc32)로 Fisher–Yates 셔플.
|
||||
- 셔플: 게임 시작 시 `crypto.getRandomValues`로 256비트 시드를 만들고, 상태 안의 암호학적 난수 생성기 ChaCha20(RFC 8439)으로 Fisher–Yates 셔플·주사위·뽑기(2026-10-11). 지금까지 나온 카드·주사위를 아무리 봐도 다음 값을 알 수 없다. 그 전에 시작된 게임은 sfc32(128비트) 그대로라 다시 보기가 같다.
|
||||
- **공정성 확인(선택 표시)**: 게임 시작 때 시드의 SHA-256 해시를 모두에게 공개하고, 게임이 끝나면 시드를 공개한다. 결과 화면의 "공정성 확인"을 누르면 같은 시드로 덱을 다시 만들어 실제 배분과 같은지 브라우저가 확인한다.
|
||||
- 관전자에게는 공개 정보만. 포커·섯다처럼 관전이 정보 누설 통로가 될 수 있는 게임은 기본적으로 "관전 지연 표시 없음 + 공개 정보만"이고, 같은 사람이 플레이어와 관전자를 동시에 할 수 없다.
|
||||
|
||||
|
||||
@@ -63,7 +63,7 @@ export interface GameDefinition<S, A, V, O> {
|
||||
- 시간은 `ctx.now`로만 받는다. 타이머가 필요한 게임은 상태에 `turnStartedAt`, `timeLeft` 같은 값을 둔다.
|
||||
|
||||
## 3. 결정적 난수
|
||||
- 알고리즘: sfc32(32비트 4개 상태). 시드는 서버가 `crypto.getRandomValues`로 128비트 생성.
|
||||
- 알고리즘: ChaCha20(RFC 8439, 상태 `[키 8개, 블록 번호, 쓴 개수, 0]`). 시드는 서버가 `crypto.getRandomValues`로 256비트 생성(2026-10-11). 32비트 4개 상태·128비트 시드는 예전 sfc32로 읽어 옛 게임 다시 보기·저장된 판이 그대로다(테스트 시드 `seedN`도 sfc32).
|
||||
- GameRunner가 저장된 RNG 상태로 `Rng`를 만들어 `ctx.rng`로 넘기고, 호출이 끝나면 새 RNG 상태를 저장한다. 게임 모듈은 RNG 상태를 직접 들고 있지 않는다.
|
||||
- 셔플은 Fisher–Yates, `rng.int`는 거부 샘플링으로 편향 없이.
|
||||
|
||||
@@ -90,7 +90,7 @@ onTimer():
|
||||
## 5. 공통 유틸 (`packages/engine`)
|
||||
| 모듈 | 내용 |
|
||||
|---|---|
|
||||
| `rng.ts` | sfc32, 시드 생성/직렬화, shuffle |
|
||||
| `rng.ts` | ChaCha20(새 게임)·sfc32(옛 게임), 시드 생성/직렬화, shuffle |
|
||||
| `cards/standard.ts` | 52장 + 조커 트럼프 카드 ID(`"S-A"`, `"H-10"`, `"JK1"`), 무늬·숫자 파싱 |
|
||||
| `cards/hwatu.ts` | 화투 48장(+보너스패) ID와 속성(월, 광/열끗/띠/피, 쌍피 등). 섯다·고스톱 공용 |
|
||||
| `turns.ts` | 시계 방향 다음 사람, 살아 있는 사람만 돌기, 선 정하기 |
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, createSeed, seedFromHex, seedToHex } from './rng';
|
||||
import { SeededRng, chachaBlock, createSeed, seedFromHex, seedToHex } from './rng';
|
||||
|
||||
describe('SeededRng', () => {
|
||||
test('is deterministic for the same seed', () => {
|
||||
@@ -34,3 +34,67 @@ describe('SeededRng', () => {
|
||||
expect(seedFromHex(seedToHex(seed))).toEqual(seed);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ChaCha20 (new games)', () => {
|
||||
test('block function matches the RFC 8439 §2.3.2 test vector', () => {
|
||||
const key = [0x03020100, 0x07060504, 0x0b0a0908, 0x0f0e0d0c, 0x13121110, 0x17161514, 0x1b1a1918, 0x1f1e1d1c];
|
||||
const out = chachaBlock(key, 1, [0x09000000, 0x4a000000, 0x00000000]);
|
||||
expect([...out].map((n) => n.toString(16).padStart(8, '0'))).toEqual([
|
||||
'e4e7f110', '15593bd1', '1fdd0f50', 'c47120a3', 'c7f4d1c7', '0368c033', '9aaa2204', '4e6cd4c3',
|
||||
'466482d2', '09aa9f07', '05d7c214', 'a2028bd9', 'd19c12b5', 'b94e16de', 'e883d0cb', '4e3c50a2',
|
||||
]);
|
||||
});
|
||||
|
||||
test('new seeds are 256 bits from the OS and pick ChaCha20; old 128-bit seeds keep sfc32', () => {
|
||||
const seed = createSeed();
|
||||
expect(seed).toHaveLength(8);
|
||||
expect(seedToHex(seed)).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(seedFromHex(seedToHex(seed))).toEqual(seed);
|
||||
expect(SeededRng.fromSeed(seed).state()).toHaveLength(11);
|
||||
expect(SeededRng.fromSeed(seedFromHex('00000001000000020000000300000004')).state()).toHaveLength(4);
|
||||
// Old games replay exactly as before.
|
||||
const old = SeededRng.fromSeed([1, 2, 3, 4]);
|
||||
expect([old.nextUint32(), old.nextUint32(), old.nextUint32()]).toEqual([417285410, 1196253302, 123583739]); // sfc32 output before 2026-10-11
|
||||
});
|
||||
|
||||
test('deterministic, and the saved state resumes exactly (also at a block boundary)', () => {
|
||||
const seed = createSeed();
|
||||
const a = SeededRng.fromSeed(seed);
|
||||
const b = SeededRng.fromSeed(seed);
|
||||
for (let i = 0; i < 100; i++) expect(a.nextUint32()).toBe(b.nextUint32());
|
||||
for (const k of [0, 1, 15, 16, 17, 31, 32, 33]) {
|
||||
const r = SeededRng.fromSeed(seed);
|
||||
for (let i = 0; i < k; i++) r.nextUint32();
|
||||
const saved = JSON.parse(JSON.stringify(r.state()));
|
||||
const resumed = new SeededRng(saved);
|
||||
for (let i = 0; i < 40; i++) expect(resumed.nextUint32()).toBe(r.nextUint32());
|
||||
}
|
||||
});
|
||||
|
||||
test('uniform: dice, cards and bits', () => {
|
||||
const r = SeededRng.fromSeed(createSeed());
|
||||
const counts = new Array(6).fill(0);
|
||||
for (let i = 0; i < 60000; i++) counts[r.int(6)]++;
|
||||
// chi-square with 5 degrees of freedom: 20.5 is the 0.1% tail.
|
||||
const chi = counts.reduce((acc, c) => acc + (c - 10000) ** 2 / 10000, 0);
|
||||
expect(chi).toBeLessThan(20.5);
|
||||
const first = new Array(52).fill(0);
|
||||
for (let i = 0; i < 52000; i++) first[r.shuffle(Array.from({ length: 52 }, (_, j) => j))[0]!]++;
|
||||
const chi52 = first.reduce((acc, c) => acc + (c - 1000) ** 2 / 1000, 0);
|
||||
expect(chi52).toBeLessThan(97); // 51 dof, 0.01% tail
|
||||
let ones = 0;
|
||||
for (let i = 0; i < 10000; i++) {
|
||||
let x = r.nextUint32();
|
||||
while (x) {
|
||||
ones += x & 1;
|
||||
x >>>= 1;
|
||||
}
|
||||
}
|
||||
expect(Math.abs(ones / 320000 - 0.5)).toBeLessThan(0.005);
|
||||
});
|
||||
|
||||
test('two games never share a seed', () => {
|
||||
const seen = new Set(Array.from({ length: 1000 }, () => seedToHex(createSeed())));
|
||||
expect(seen.size).toBe(1000);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
/**
|
||||
* Deterministic seeded PRNG (sfc32). The state is four 32-bit unsigned ints and is
|
||||
* JSON-serialisable so it can be persisted next to the game state (docs/09 §3).
|
||||
* Deterministic seeded random numbers, JSON-serialisable so the state is persisted next to the game state (docs/09 §3)
|
||||
* and a whole game can be replayed and checked from its seed (docs/04 §5).
|
||||
*
|
||||
* New games (2026-10-11): ChaCha20 (RFC 8439) keyed by a 256-bit seed from the OS (`crypto.getRandomValues`).
|
||||
* It is a cryptographic generator: seeing any number of dice, cards or tiles tells nothing about the next ones
|
||||
* (sfc32 is fast but its state can be worked out from enough outputs). Games started before keep sfc32 (4-word
|
||||
* seeds/states), so their replays and saved games stay exactly the same.
|
||||
*
|
||||
* State layouts: sfc32 `[a, b, c, d]`; ChaCha20 seed `[k0..k7]`, state `[k0..k7, block, used, 0]`.
|
||||
*/
|
||||
export type RngState = [number, number, number, number];
|
||||
export type Sfc32State = [number, number, number, number];
|
||||
export type ChaChaSeed = [number, number, number, number, number, number, number, number];
|
||||
export type ChaChaState = [number, number, number, number, number, number, number, number, number, number, number];
|
||||
export type RngState = Sfc32State | ChaChaSeed | ChaChaState;
|
||||
|
||||
export interface Rng {
|
||||
/** Float in [0, 1). */
|
||||
@@ -13,46 +23,99 @@ export interface Rng {
|
||||
shuffle<T>(arr: readonly T[]): T[];
|
||||
}
|
||||
|
||||
export function createSeed(): RngState {
|
||||
const buf = new Uint32Array(4);
|
||||
/** A fresh 256-bit seed from the operating system's secure random source. */
|
||||
export function createSeed(): ChaChaSeed {
|
||||
const buf = new Uint32Array(8);
|
||||
crypto.getRandomValues(buf);
|
||||
// An all-zero state would be degenerate for sfc32's counter; guard anyway.
|
||||
if (buf[0] === 0 && buf[1] === 0 && buf[2] === 0 && buf[3] === 0) buf[3] = 1;
|
||||
return [buf[0]!, buf[1]!, buf[2]!, buf[3]!];
|
||||
return [...buf] as ChaChaSeed;
|
||||
}
|
||||
|
||||
export function seedToHex(seed: RngState): string {
|
||||
return seed.map((n) => (n >>> 0).toString(16).padStart(8, '0')).join('');
|
||||
}
|
||||
|
||||
export function seedFromHex(hex: string): RngState {
|
||||
if (!/^[0-9a-f]{32}$/.test(hex)) throw new Error('invalid seed hex');
|
||||
return [0, 1, 2, 3].map((i) => parseInt(hex.slice(i * 8, i * 8 + 8), 16) >>> 0) as RngState;
|
||||
/** 32 hex digits = an sfc32 seed (older games), 64 = a ChaCha20 seed. */
|
||||
export function seedFromHex(hex: string): Sfc32State | ChaChaSeed {
|
||||
if (!/^([0-9a-f]{32}|[0-9a-f]{64})$/.test(hex)) throw new Error('invalid seed hex');
|
||||
return Array.from({ length: hex.length / 8 }, (_, i) => parseInt(hex.slice(i * 8, i * 8 + 8), 16) >>> 0) as Sfc32State | ChaChaSeed;
|
||||
}
|
||||
|
||||
/** Mutable PRNG over a copy of `state`; read the advanced state back with `rng.state()`. */
|
||||
const rotl = (x: number, n: number) => ((x << n) | (x >>> (32 - n))) >>> 0;
|
||||
|
||||
/** ChaCha20 block (RFC 8439 §2.3) for `key`, block counter `counter`, nonce 0. Exported for the test vector. */
|
||||
export function chachaBlock(key: readonly number[], counter: number, nonce: readonly number[] = [0, 0, 0]): Uint32Array {
|
||||
const init = [0x61707865, 0x3320646e, 0x79622d32, 0x6b206574, ...key.map((k) => k >>> 0), counter >>> 0, ...nonce.map((n) => n >>> 0)];
|
||||
const x = Uint32Array.from(init);
|
||||
const qr = (a: number, b: number, c: number, d: number) => {
|
||||
x[a] = (x[a]! + x[b]!) >>> 0;
|
||||
x[d] = rotl(x[d]! ^ x[a]!, 16);
|
||||
x[c] = (x[c]! + x[d]!) >>> 0;
|
||||
x[b] = rotl(x[b]! ^ x[c]!, 12);
|
||||
x[a] = (x[a]! + x[b]!) >>> 0;
|
||||
x[d] = rotl(x[d]! ^ x[a]!, 8);
|
||||
x[c] = (x[c]! + x[d]!) >>> 0;
|
||||
x[b] = rotl(x[b]! ^ x[c]!, 7);
|
||||
};
|
||||
for (let i = 0; i < 10; i++) {
|
||||
qr(0, 4, 8, 12);
|
||||
qr(1, 5, 9, 13);
|
||||
qr(2, 6, 10, 14);
|
||||
qr(3, 7, 11, 15);
|
||||
qr(0, 5, 10, 15);
|
||||
qr(1, 6, 11, 12);
|
||||
qr(2, 7, 8, 13);
|
||||
qr(3, 4, 9, 14);
|
||||
}
|
||||
for (let i = 0; i < 16; i++) x[i] = (x[i]! + init[i]!) >>> 0;
|
||||
return x;
|
||||
}
|
||||
|
||||
/** Mutable generator over a copy of `state`; read the advanced state back with `rng.state()`. */
|
||||
export class SeededRng implements Rng {
|
||||
private a: number;
|
||||
private b: number;
|
||||
private c: number;
|
||||
private d: number;
|
||||
private a = 0;
|
||||
private b = 0;
|
||||
private c = 0;
|
||||
private d = 0;
|
||||
/** ChaCha20: key, current block number and words of it already used; null for sfc32. */
|
||||
private key: number[] | null = null;
|
||||
private blockNo = 0;
|
||||
private used = 16;
|
||||
private block: Uint32Array | null = null;
|
||||
|
||||
constructor(state: RngState) {
|
||||
[this.a, this.b, this.c, this.d] = state.map((n) => n >>> 0) as RngState;
|
||||
if (state.length === 4) {
|
||||
[this.a, this.b, this.c, this.d] = state.map((n) => n >>> 0) as Sfc32State;
|
||||
} else if (state.length === 11) {
|
||||
this.key = state.slice(0, 8).map((n) => n >>> 0);
|
||||
this.blockNo = state[8] >>> 0;
|
||||
this.used = state[9];
|
||||
} else throw new Error(`SeededRng: bad state length ${(state as number[]).length}`);
|
||||
}
|
||||
|
||||
/** Seeds from a hex string, running a few warm-up rounds as recommended for sfc32. */
|
||||
static fromSeed(seed: RngState): SeededRng {
|
||||
/** sfc32 seeds run a few warm-up rounds as recommended; ChaCha20 seeds start at block 0. */
|
||||
static fromSeed(seed: Sfc32State | ChaChaSeed | RngState): SeededRng {
|
||||
if (seed.length === 8) return new SeededRng([...seed, 0, 0, 0] as ChaChaState);
|
||||
const rng = new SeededRng(seed);
|
||||
for (let i = 0; i < 12; i++) rng.nextUint32();
|
||||
return rng;
|
||||
}
|
||||
|
||||
state(): RngState {
|
||||
if (this.key) return [...this.key, this.blockNo, this.used, 0] as ChaChaState;
|
||||
return [this.a, this.b, this.c, this.d];
|
||||
}
|
||||
|
||||
nextUint32(): number {
|
||||
if (this.key) {
|
||||
if (this.used >= 16) {
|
||||
// This block is used up (also right after restoring a state saved at its end): move to the next one.
|
||||
this.blockNo = (this.blockNo + 1) >>> 0;
|
||||
this.used = 0;
|
||||
this.block = null;
|
||||
}
|
||||
this.block ??= chachaBlock(this.key, this.blockNo);
|
||||
return this.block[this.used++]!;
|
||||
}
|
||||
const t = (((this.a + this.b) >>> 0) + this.d) >>> 0;
|
||||
this.d = (this.d + 1) >>> 0;
|
||||
this.a = this.b ^ (this.b >>> 9);
|
||||
|
||||
@@ -371,6 +371,23 @@ describe('조커 (§5.1, §5.2)', () => {
|
||||
expect(shown(s, 'A')).toEqual([false, false, false]);
|
||||
expect(davinci.view(s, 'B').rows.A![2]).toEqual({ color: 'white', revealed: false, wrong: [] });
|
||||
});
|
||||
|
||||
test('조커를 놓는 중이라는 걸 남은 모른다: 상대·관전자 화면은 바로 전 단계(멈추기 전 / 추리)로 보인다', () => {
|
||||
let s = rigged({ A: ['b1', 'w4'], B: ['b0', 'w3'] }, { jokers: true }, { white: ['wJ', 'w5'] });
|
||||
s = act(s, 'A', { type: 'draw', color: 'white' });
|
||||
s = act(s, 'A', guess('B', 0, 0));
|
||||
s = act(s, 'A', { type: 'stop' });
|
||||
expect(davinci.view(s, 'A').phase).toBe('placeJoker');
|
||||
expect(davinci.view(s, 'B').phase).toBe('afterCorrect');
|
||||
expect(davinci.view(s, null).phase).toBe('afterCorrect');
|
||||
expect(JSON.stringify(davinci.view(s, 'B'))).not.toMatch(/placeJoker|"n":"joker"|wJ/);
|
||||
// Wrong guess with a drawn joker: the others still see "guessing" until it is placed (face up).
|
||||
let t = rigged({ A: ['b1', 'w4'], B: ['b0', 'w3'] }, { jokers: true }, { white: ['wJ', 'w5'] });
|
||||
t = act(t, 'A', { type: 'draw', color: 'white' });
|
||||
t = act(t, 'A', guess('B', 0, 7));
|
||||
expect(davinci.view(t, 'A').phase).toBe('placeJoker');
|
||||
expect(davinci.view(t, 'B').phase).toBe('guess');
|
||||
});
|
||||
});
|
||||
|
||||
describe('거부 (§8.2)', () => {
|
||||
|
||||
@@ -706,7 +706,9 @@ export const davinci: GameDefinition<DavinciState, DavinciAction, DavinciView, D
|
||||
options: s.options,
|
||||
me,
|
||||
seats: s.seats,
|
||||
phase: ph.kind,
|
||||
// Placing a drawn joker is secret: the others see the step before it (after 멈추기 → still deciding; after a
|
||||
// wrong guess → still guessing), never "조커를 넣는 중".
|
||||
phase: ph.kind === 'placeJoker' && me !== s.current ? (ph.reveal ? 'guess' : 'afterCorrect') : ph.kind,
|
||||
current: s.current,
|
||||
startCount: s.startCount,
|
||||
rows,
|
||||
|
||||
Reference in New Issue
Block a user