Новогодний квиз: ядро, сервер и три экрана
- ядро: контент, reducer всех фаз, undo, проекции по ролям - сервер: комнаты, сокеты, таймеры, раздача интерфейса и медиа - интерфейс: табло, пульт ведущего, телефон игрока - контент: пак 5x5 с финалом и демо-пак с рабочим аудио - 57 тестов и e2e на трёх вкладках
This commit is contained in:
commit
89eeea4855
54 files changed
+12010
No files matched your search
@@ -0,0 +1,219 @@
|
||||
/**
|
||||
* Валидация контента.
|
||||
*
|
||||
* Пак — это данные, которые пишет человек руками, поэтому схема обязана
|
||||
* ловить опечатки до игры, а не в момент показа вопроса на проекторе.
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync, readdirSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { Pack } from '../src/index'
|
||||
import { cellKey, effectiveValue, findCell, isRoundComplete, parseCellKey, parsePack } from '../src/index'
|
||||
|
||||
const CONTENT_DIR = fileURLToPath(new URL('../../../content/', import.meta.url))
|
||||
const PACKS_DIR = path.join(CONTENT_DIR, 'packs')
|
||||
|
||||
function loadDemo(): unknown {
|
||||
return JSON.parse(readFileSync(path.join(PACKS_DIR, 'demo.json'), 'utf8'))
|
||||
}
|
||||
|
||||
function packFiles(): string[] {
|
||||
return readdirSync(PACKS_DIR).filter((file) => file.endsWith('.json'))
|
||||
}
|
||||
|
||||
function mediaSources(pack: Pack): string[] {
|
||||
const sources: string[] = []
|
||||
for (const round of pack.rounds) {
|
||||
for (const theme of round.themes) {
|
||||
for (const cell of theme.cells) {
|
||||
if (cell.question.media) sources.push(cell.question.media.src)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pack.final?.question.media) sources.push(pack.final.question.media.src)
|
||||
return sources
|
||||
}
|
||||
|
||||
function errorsOf(input: unknown): string[] {
|
||||
const result = parsePack(input)
|
||||
if (result.ok) throw new Error('ожидалась ошибка валидации, а пак прошёл')
|
||||
return result.errors
|
||||
}
|
||||
|
||||
function validPack(): Record<string, unknown> {
|
||||
return {
|
||||
id: 'demo',
|
||||
title: 'Демо',
|
||||
settings: {},
|
||||
rounds: [
|
||||
{
|
||||
id: 'r1',
|
||||
title: 'Раунд 1',
|
||||
themes: [
|
||||
{
|
||||
id: 't1',
|
||||
title: 'Тема 1',
|
||||
cells: [{ value: 100, question: { text: 'Вопрос', answer: 'Ответ' } }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
describe('все паки в репозитории', () => {
|
||||
const files = packFiles()
|
||||
|
||||
it('их вообще есть', () => {
|
||||
expect(files.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
for (const file of files) {
|
||||
it(`${file}: проходит схему`, () => {
|
||||
const raw: unknown = JSON.parse(readFileSync(path.join(PACKS_DIR, file), 'utf8'))
|
||||
const result = parsePack(raw)
|
||||
if (!result.ok) throw new Error(`${file}:\n${result.errors.join('\n')}`)
|
||||
|
||||
for (const round of result.pack.rounds) {
|
||||
const sizes = new Set(round.themes.map((theme) => theme.cells.length))
|
||||
expect(sizes.size).toBe(1)
|
||||
}
|
||||
})
|
||||
|
||||
it(`${file}: все медиафайлы лежат на диске`, () => {
|
||||
// Самый обидный баг вечера — вопрос с музыкой, у которого нет файла.
|
||||
const raw: unknown = JSON.parse(readFileSync(path.join(PACKS_DIR, file), 'utf8'))
|
||||
const result = parsePack(raw)
|
||||
if (!result.ok) throw new Error(`${file}:\n${result.errors.join('\n')}`)
|
||||
|
||||
for (const source of mediaSources(result.pack)) {
|
||||
const relative = source.replace(/^\/media\//, '')
|
||||
const full = path.join(CONTENT_DIR, 'media', relative)
|
||||
expect(existsSync(full), `нет файла для ${source} (${file})`).toBe(true)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
describe('демо-пак', () => {
|
||||
it('проходит валидацию и готов к игре', () => {
|
||||
const result = parsePack(loadDemo())
|
||||
if (!result.ok) throw new Error(result.errors.join('\n'))
|
||||
const pack = result.pack
|
||||
|
||||
expect(pack.rounds.length).toBeGreaterThan(0)
|
||||
expect(pack.final).toBeDefined()
|
||||
|
||||
for (const round of pack.rounds) {
|
||||
const sizes = new Set(round.themes.map((t) => t.cells.length))
|
||||
expect(sizes.size).toBe(1)
|
||||
for (const theme of round.themes) {
|
||||
for (const cell of theme.cells) {
|
||||
expect(cell.question.answer.length).toBeGreaterThan(0)
|
||||
expect(Boolean(cell.question.text || cell.question.media)).toBe(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('заполняет значения по умолчанию', () => {
|
||||
const result = parsePack(loadDemo())
|
||||
if (!result.ok) throw new Error(result.errors.join('\n'))
|
||||
expect(result.pack.settings.defaultTimeLimit).toBe(30)
|
||||
expect(result.pack.settings.buzzers).toBe(true)
|
||||
const firstCell = result.pack.rounds[0]?.themes[0]?.cells[0]
|
||||
expect(firstCell?.kind).toBe('normal')
|
||||
})
|
||||
})
|
||||
|
||||
describe('схема ловит ошибки автора', () => {
|
||||
it('повторяющийся номинал в теме', () => {
|
||||
const pack = validPack()
|
||||
const round = (pack.rounds as any[])[0]
|
||||
round.themes[0].cells.push({ value: 100, question: { text: 'Ещё', answer: 'Ответ' } })
|
||||
expect(errorsOf(pack).join(' ')).toMatch(/повторяется номинал 100/)
|
||||
})
|
||||
|
||||
it('разное число клеток у тем', () => {
|
||||
const pack = validPack()
|
||||
const round = (pack.rounds as any[])[0]
|
||||
round.themes.push({
|
||||
id: 't2',
|
||||
title: 'Тема 2',
|
||||
cells: [
|
||||
{ value: 100, question: { text: 'Вопрос', answer: 'Ответ' } },
|
||||
{ value: 200, question: { text: 'Вопрос', answer: 'Ответ' } },
|
||||
],
|
||||
})
|
||||
expect(errorsOf(pack).join(' ')).toMatch(/одинаковое число клеток/)
|
||||
})
|
||||
|
||||
it('вопрос без текста и без медиа', () => {
|
||||
const pack = validPack()
|
||||
const round = (pack.rounds as any[])[0]
|
||||
round.themes[0].cells[0].question = { answer: 'Ответ' }
|
||||
expect(errorsOf(pack).join(' ')).toMatch(/text или media/)
|
||||
})
|
||||
|
||||
it('медиа вне /media/', () => {
|
||||
const pack = validPack()
|
||||
const round = (pack.rounds as any[])[0]
|
||||
round.themes[0].cells[0].question = {
|
||||
media: { kind: 'audio', src: 'https://example.com/song.mp3' },
|
||||
answer: 'Ответ',
|
||||
}
|
||||
expect(errorsOf(pack).join(' ')).toMatch(/\/media\//)
|
||||
})
|
||||
|
||||
it('финал задан, но выключен', () => {
|
||||
const pack = validPack()
|
||||
pack.settings = { finalEnabled: false }
|
||||
pack.final = { question: { text: 'Финал', answer: 'Ответ' } }
|
||||
expect(errorsOf(pack).join(' ')).toMatch(/finalEnabled/)
|
||||
})
|
||||
|
||||
it('неизвестный тип клетки', () => {
|
||||
const pack = validPack()
|
||||
const round = (pack.rounds as any[])[0]
|
||||
round.themes[0].cells[0].kind = 'bonus'
|
||||
expect(errorsOf(pack).length).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('навигация по сетке', () => {
|
||||
it('ключ клетки переживает разбор', () => {
|
||||
const key = cellKey('r1', 't1', 2)
|
||||
expect(key).toBe('r1/t1/2')
|
||||
expect(parseCellKey(key)).toEqual({ roundId: 'r1', themeId: 't1', index: 2 })
|
||||
expect(parseCellKey('мусор')).toBeNull()
|
||||
expect(parseCellKey('r1/t1/нет')).toBeNull()
|
||||
})
|
||||
|
||||
it('findCell находит клетку и стоимость с учётом супер-вопроса', () => {
|
||||
const result = parsePack(loadDemo())
|
||||
if (!result.ok) throw new Error(result.errors.join('\n'))
|
||||
const pack = result.pack
|
||||
|
||||
const found = findCell(pack, 'r1/cinema/2')
|
||||
expect(found?.cell.kind).toBe('super')
|
||||
expect(found && effectiveValue(found.cell)).toBe(600)
|
||||
|
||||
expect(findCell(pack, 'r1/нет-такой/0')).toBeNull()
|
||||
expect(findCell(pack, 'r1/cinema/99')).toBeNull()
|
||||
})
|
||||
|
||||
it('раунд считается сыгранным только когда закрыты все клетки', () => {
|
||||
const result = parsePack(loadDemo())
|
||||
if (!result.ok) throw new Error(result.errors.join('\n'))
|
||||
const round = result.pack.rounds[0]
|
||||
if (!round) throw new Error('нет раунда')
|
||||
|
||||
const keys = round.themes.flatMap((theme) =>
|
||||
theme.cells.map((_, index) => cellKey(round.id, theme.id, index)),
|
||||
)
|
||||
expect(isRoundComplete(round, keys.slice(0, -1))).toBe(false)
|
||||
expect(isRoundComplete(round, keys)).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,465 @@
|
||||
/**
|
||||
* Сценарии партии целиком: без сети, без браузера, с подменёнными часами.
|
||||
*
|
||||
* Каждый тест — это то, что ведущий реально делает за вечер. Если сценарий
|
||||
* зелёный здесь, в игре он сломается только из-за сети.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { Actor, Cell, Pack, PackSettings, Result } from '../src/index'
|
||||
import { GameEngine, project } from '../src/index'
|
||||
|
||||
const HOST: Actor = { id: 'host', role: 'host' }
|
||||
const SYSTEM: Actor = { id: 'system', role: 'system' }
|
||||
const p1: Actor = { id: 'p1', role: 'player' }
|
||||
const p2: Actor = { id: 'p2', role: 'player' }
|
||||
|
||||
const SETTINGS: PackSettings = {
|
||||
wrongPenalty: 'value',
|
||||
buzzers: true,
|
||||
finalEnabled: true,
|
||||
defaultTimeLimit: 30,
|
||||
answerTimeLimit: 20,
|
||||
auctionTimeLimit: 30,
|
||||
betTimeLimit: 20,
|
||||
}
|
||||
|
||||
function cell(value: number, kind: Cell['kind'] = 'normal'): Cell {
|
||||
return { value, kind, question: { text: `Вопрос за ${value}`, answer: `Ответ ${value}` } }
|
||||
}
|
||||
|
||||
/** Один раунд, две темы по три клетки — покрывают normal, cat_in_bag, auction, super. */
|
||||
function makePack(): Pack {
|
||||
return {
|
||||
id: 'test',
|
||||
title: 'Тестовый пак',
|
||||
// Копия обязательна: тесты меняют настройки, а общий объект протёк бы между ними.
|
||||
settings: { ...SETTINGS },
|
||||
rounds: [
|
||||
{
|
||||
id: 'r1',
|
||||
title: 'Раунд 1',
|
||||
themes: [
|
||||
{ id: 't1', title: 'Тема 1', cells: [cell(100), cell(200), cell(300)] },
|
||||
{
|
||||
id: 't2',
|
||||
title: 'Тема 2',
|
||||
cells: [cell(100, 'cat_in_bag'), cell(200, 'auction'), cell(300, 'super')],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
final: { question: { text: 'Финальный вопрос', answer: 'Финальный ответ' } },
|
||||
}
|
||||
}
|
||||
|
||||
const KEYS = ['r1/t1/0', 'r1/t1/1', 'r1/t1/2', 'r1/t2/0', 'r1/t2/1', 'r1/t2/2']
|
||||
|
||||
function expectOk(result: Result): Extract<Result, { ok: true }> {
|
||||
if (!result.ok) throw new Error(`ожидался успех, а пришла ошибка: ${result.reason}`)
|
||||
return result
|
||||
}
|
||||
|
||||
function expectFail(result: Result): string {
|
||||
if (result.ok) throw new Error('ожидалась ошибка, а команда прошла')
|
||||
return result.reason
|
||||
}
|
||||
|
||||
interface Setup {
|
||||
engine: GameEngine
|
||||
clock: { value: number }
|
||||
}
|
||||
|
||||
function setup(): Setup {
|
||||
const clock = { value: 1_000_000 }
|
||||
const engine = new GameEngine(makePack(), { now: () => clock.value })
|
||||
for (const [id, name] of [
|
||||
['p1', 'Аня'],
|
||||
['p2', 'Боря'],
|
||||
] as const) {
|
||||
expectOk(engine.dispatch({ type: 'addPlayer', playerId: id, name }, { actor: SYSTEM }))
|
||||
}
|
||||
expectOk(engine.dispatch({ type: 'startGame' }, { actor: HOST }))
|
||||
expectOk(engine.dispatch({ type: 'next' }, { actor: HOST }))
|
||||
return { engine, clock }
|
||||
}
|
||||
|
||||
/** Ведущий принудительно закрывает клетку: назначил игрока и снял вопрос. */
|
||||
function skipCell(engine: GameEngine, key: string): void {
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: key }, { actor: HOST }))
|
||||
// У «кота в мешке» нельзя назначить того, кто открыл клетку, — берём другого.
|
||||
const target = engine.current.active?.by === 'p1' ? 'p2' : 'p1'
|
||||
expectOk(engine.dispatch({ type: 'nominate', playerId: target }, { actor: HOST }))
|
||||
expectOk(engine.dispatch({ type: 'judge', verdict: 'skip' }, { actor: HOST }))
|
||||
expectOk(engine.dispatch({ type: 'next' }, { actor: HOST }))
|
||||
}
|
||||
|
||||
describe('партия целиком', () => {
|
||||
it('проходит от лобби до результатов', () => {
|
||||
const { engine } = setup()
|
||||
expect(engine.current.phase).toBe('board')
|
||||
expect(engine.current.turn).toBe('p1')
|
||||
|
||||
// Первая клетка — честный ответ на 100.
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t1/0' }, { actor: p1 }))
|
||||
expect(engine.current.phase).toBe('question')
|
||||
|
||||
expectOk(engine.dispatch({ type: 'buzz' }, { actor: p1 }))
|
||||
expect(engine.current.phase).toBe('answering')
|
||||
expect(engine.current.answerer).toBe('p1')
|
||||
|
||||
expectOk(engine.dispatch({ type: 'judge', verdict: 'correct' }, { actor: HOST }))
|
||||
expect(engine.current.phase).toBe('reveal')
|
||||
expect(engine.current.closed).toContain('r1/t1/0')
|
||||
expect(engine.current.turn).toBe('p1')
|
||||
|
||||
const anya = engine.current.players.find((p) => p.id === 'p1')
|
||||
expect(anya?.score).toBe(100)
|
||||
|
||||
// Остальные клетки закрываем снятием вопроса.
|
||||
expectOk(engine.dispatch({ type: 'next' }, { actor: HOST }))
|
||||
for (const key of KEYS.slice(1)) skipCell(engine, key)
|
||||
|
||||
expect(engine.current.phase).toBe('round_end')
|
||||
expect(engine.current.closed).toHaveLength(KEYS.length)
|
||||
|
||||
// Финал: ставки, вопрос, вскрытие.
|
||||
expectOk(engine.dispatch({ type: 'next' }, { actor: HOST }))
|
||||
expect(engine.current.phase).toBe('final_bet')
|
||||
expectOk(engine.dispatch({ type: 'bet', amount: 50 }, { actor: p1 }))
|
||||
expectOk(engine.dispatch({ type: 'bet', amount: 100 }, { actor: p2 }))
|
||||
expect(engine.current.phase).toBe('final_question')
|
||||
|
||||
expectOk(engine.dispatch({ type: 'next' }, { actor: HOST }))
|
||||
expect(engine.current.phase).toBe('final_reveal')
|
||||
expectOk(engine.dispatch({ type: 'judge', verdict: 'correct', playerId: 'p2' }, { actor: HOST }))
|
||||
|
||||
const boris = engine.current.players.find((p) => p.id === 'p2')
|
||||
expect(boris?.score).toBe(100)
|
||||
|
||||
expectOk(engine.dispatch({ type: 'next' }, { actor: HOST }))
|
||||
expect(engine.current.phase).toBe('results')
|
||||
})
|
||||
|
||||
it('удваивает номинал у супер-вопроса', () => {
|
||||
const { engine } = setup()
|
||||
// r1/t2/2 — супер за 300, ответ должен принести 600.
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t2/2' }, { actor: p1 }))
|
||||
expectOk(engine.dispatch({ type: 'buzz' }, { actor: p1 }))
|
||||
expectOk(engine.dispatch({ type: 'judge', verdict: 'correct' }, { actor: HOST }))
|
||||
expect(engine.current.players.find((p) => p.id === 'p1')?.score).toBe(600)
|
||||
})
|
||||
})
|
||||
|
||||
describe('неверный ответ', () => {
|
||||
it('штрафует, возвращает вопрос в игру и блокирует повторное нажатие', () => {
|
||||
const { engine } = setup()
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t1/0' }, { actor: p1 }))
|
||||
expectOk(engine.dispatch({ type: 'buzz' }, { actor: p1 }))
|
||||
expectOk(engine.dispatch({ type: 'judge', verdict: 'wrong' }, { actor: HOST }))
|
||||
|
||||
expect(engine.current.phase).toBe('question')
|
||||
expect(engine.current.penalized).toContain('p1')
|
||||
expect(engine.current.players.find((p) => p.id === 'p1')?.score).toBe(-100)
|
||||
expect(engine.current.answerer).toBeUndefined()
|
||||
|
||||
// Тот же игрок второй раз нажать не может…
|
||||
const reason = expectFail(engine.dispatch({ type: 'buzz' }, { actor: p1 }))
|
||||
expect(reason).toMatch(/уже отвечали/)
|
||||
|
||||
// …а второй игрок может, и забирает очки.
|
||||
expectOk(engine.dispatch({ type: 'buzz' }, { actor: p2 }))
|
||||
expectOk(engine.dispatch({ type: 'judge', verdict: 'correct' }, { actor: HOST }))
|
||||
expect(engine.current.players.find((p) => p.id === 'p2')?.score).toBe(100)
|
||||
expect(engine.current.phase).toBe('reveal')
|
||||
})
|
||||
|
||||
it('ведущий может снять вопрос, не дожидаясь таймера', () => {
|
||||
const { engine } = setup()
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t1/0' }, { actor: p1 }))
|
||||
expect(engine.current.answerer).toBeUndefined()
|
||||
|
||||
expectOk(engine.dispatch({ type: 'judge', verdict: 'skip' }, { actor: HOST }))
|
||||
|
||||
expect(engine.current.phase).toBe('reveal')
|
||||
expect(engine.current.closed).toContain('r1/t1/0')
|
||||
expect(engine.current.players.every((p) => p.score === 0)).toBe(true)
|
||||
})
|
||||
|
||||
it('закрывает вопрос, когда ответить больше некому', () => {
|
||||
const { engine } = setup()
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t1/0' }, { actor: p1 }))
|
||||
expectOk(engine.dispatch({ type: 'buzz' }, { actor: p1 }))
|
||||
expectOk(engine.dispatch({ type: 'judge', verdict: 'wrong' }, { actor: HOST }))
|
||||
expectOk(engine.dispatch({ type: 'buzz' }, { actor: p2 }))
|
||||
expectOk(engine.dispatch({ type: 'judge', verdict: 'wrong' }, { actor: HOST }))
|
||||
|
||||
expect(engine.current.phase).toBe('reveal')
|
||||
expect(engine.current.closed).toContain('r1/t1/0')
|
||||
})
|
||||
|
||||
it('без штрафа очки не меняются', () => {
|
||||
const clock = { value: 1_000_000 }
|
||||
const pack = makePack()
|
||||
pack.settings.wrongPenalty = 'none'
|
||||
const engine = new GameEngine(pack, { now: () => clock.value })
|
||||
expectOk(engine.dispatch({ type: 'addPlayer', playerId: 'p1', name: 'Аня' }, { actor: SYSTEM }))
|
||||
expectOk(engine.dispatch({ type: 'startGame' }, { actor: HOST }))
|
||||
expectOk(engine.dispatch({ type: 'next' }, { actor: HOST }))
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t1/0' }, { actor: p1 }))
|
||||
expectOk(engine.dispatch({ type: 'buzz' }, { actor: p1 }))
|
||||
expectOk(engine.dispatch({ type: 'judge', verdict: 'wrong' }, { actor: HOST }))
|
||||
expect(engine.current.players[0]?.score).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('кот в мешке', () => {
|
||||
it('передать вопрос может только открывший клетку и не себе', () => {
|
||||
const { engine } = setup()
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t2/0' }, { actor: p1 }))
|
||||
expect(engine.current.phase).toBe('cat_nominate')
|
||||
|
||||
expect(expectFail(engine.dispatch({ type: 'nominate', playerId: 'p2' }, { actor: p2 }))).toMatch(
|
||||
/только открывший/,
|
||||
)
|
||||
expect(expectFail(engine.dispatch({ type: 'nominate', playerId: 'p1' }, { actor: p1 }))).toMatch(
|
||||
/самому себе/,
|
||||
)
|
||||
|
||||
expectOk(engine.dispatch({ type: 'nominate', playerId: 'p2' }, { actor: p1 }))
|
||||
expect(engine.current.phase).toBe('answering')
|
||||
expect(engine.current.answerer).toBe('p2')
|
||||
})
|
||||
|
||||
it('не даёт нажать кнопку во время передачи', () => {
|
||||
const { engine } = setup()
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t2/0' }, { actor: p1 }))
|
||||
expect(expectFail(engine.dispatch({ type: 'buzz' }, { actor: p2 }))).toMatch(/нельзя нажать/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('аукцион', () => {
|
||||
it('играет на ставку победителя, а не на номинал', () => {
|
||||
const { engine } = setup()
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t2/1' }, { actor: p1 }))
|
||||
expect(engine.current.phase).toBe('auction')
|
||||
|
||||
expectOk(engine.dispatch({ type: 'bet', amount: 150 }, { actor: p1 }))
|
||||
expect(engine.current.phase).toBe('auction')
|
||||
expectOk(engine.dispatch({ type: 'bet', amount: 50 }, { actor: p2 }))
|
||||
|
||||
expect(engine.current.phase).toBe('answering')
|
||||
expect(engine.current.answerer).toBe('p1')
|
||||
expect(engine.current.stake).toBe(150)
|
||||
|
||||
expectOk(engine.dispatch({ type: 'judge', verdict: 'correct' }, { actor: HOST }))
|
||||
expect(engine.current.players.find((p) => p.id === 'p1')?.score).toBe(150)
|
||||
})
|
||||
|
||||
it('не даёт поставить больше номинала', () => {
|
||||
const { engine } = setup()
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t2/1' }, { actor: p1 }))
|
||||
expect(expectFail(engine.dispatch({ type: 'bet', amount: 500 }, { actor: p1 }))).toMatch(
|
||||
/больше номинала/,
|
||||
)
|
||||
})
|
||||
|
||||
it('ведущий может поставить за игрока, если тот не успевает', () => {
|
||||
const { engine } = setup()
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t2/1' }, { actor: p1 }))
|
||||
expectOk(engine.dispatch({ type: 'bet', amount: 120, playerId: 'p2' }, { actor: HOST }))
|
||||
expect(engine.current.bets['p2']).toBe(120)
|
||||
|
||||
// Без указания игрока ставка ведущего не имеет смысла.
|
||||
expect(expectFail(engine.dispatch({ type: 'bet', amount: 50 }, { actor: HOST }))).toMatch(
|
||||
/указать игрока/,
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('сброс партии', () => {
|
||||
it('возвращает в лобби, обнуляет очки и оставляет игроков', () => {
|
||||
const { engine } = setup()
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t1/0' }, { actor: p1 }))
|
||||
expectOk(engine.dispatch({ type: 'buzz' }, { actor: p1 }))
|
||||
expectOk(engine.dispatch({ type: 'judge', verdict: 'correct' }, { actor: HOST }))
|
||||
expect(engine.current.players[0]?.score).toBe(100)
|
||||
|
||||
expectOk(engine.dispatch({ type: 'resetGame' }, { actor: HOST }))
|
||||
|
||||
expect(engine.current.phase).toBe('lobby')
|
||||
expect(engine.current.closed).toEqual([])
|
||||
expect(engine.current.players).toHaveLength(2)
|
||||
expect(engine.current.players.every((player) => player.score === 0)).toBe(true)
|
||||
expect(engine.current.turn).toBe('p1')
|
||||
})
|
||||
|
||||
it('не даёт сбросить игроку и не сбрасывает уже пустое лобби', () => {
|
||||
const { engine } = setup()
|
||||
expect(expectFail(engine.dispatch({ type: 'resetGame' }, { actor: p1 }))).toMatch(
|
||||
/только ведущий/,
|
||||
)
|
||||
expectOk(engine.dispatch({ type: 'resetGame' }, { actor: HOST }))
|
||||
expect(expectFail(engine.dispatch({ type: 'resetGame' }, { actor: HOST }))).toMatch(
|
||||
/ещё не начиналась/,
|
||||
)
|
||||
})
|
||||
|
||||
it('выбрасывает отключившихся: за столом только подключённые', () => {
|
||||
const { engine } = setup()
|
||||
expectOk(engine.dispatch({ type: 'removePlayer', playerId: 'p2' }, { actor: SYSTEM }))
|
||||
expectOk(engine.dispatch({ type: 'resetGame' }, { actor: HOST }))
|
||||
|
||||
expect(engine.current.players.map((player) => player.id)).toEqual(['p1'])
|
||||
expect(engine.current.turn).toBe('p1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('таймеры', () => {
|
||||
it('по истечении времени закрывает вопрос без штрафа', () => {
|
||||
const { engine, clock } = setup()
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t1/0' }, { actor: p1 }))
|
||||
const deadline = engine.current.deadline
|
||||
expect(deadline).toBe(clock.value + 30_000)
|
||||
|
||||
clock.value += 30_001
|
||||
expectOk(engine.dispatch({ type: 'tick' }, { actor: SYSTEM }))
|
||||
|
||||
expect(engine.current.phase).toBe('reveal')
|
||||
expect(engine.current.closed).toContain('r1/t1/0')
|
||||
expect(engine.current.players.find((p) => p.id === 'p1')?.score).toBe(0)
|
||||
})
|
||||
|
||||
it('до истечения tick ничего не меняет и не двигает версию', () => {
|
||||
const { engine, clock } = setup()
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t1/0' }, { actor: p1 }))
|
||||
const before = engine.current
|
||||
clock.value += 1_000
|
||||
const result = expectOk(engine.dispatch({ type: 'tick' }, { actor: SYSTEM }))
|
||||
expect(result.state).toBe(before)
|
||||
expect(engine.current.seq).toBe(before.seq)
|
||||
})
|
||||
|
||||
it('просроченный ответ игрока трактуется как неверный', () => {
|
||||
const { engine, clock } = setup()
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t1/0' }, { actor: p1 }))
|
||||
expectOk(engine.dispatch({ type: 'buzz' }, { actor: p1 }))
|
||||
clock.value += 20_001
|
||||
expectOk(engine.dispatch({ type: 'tick' }, { actor: SYSTEM }))
|
||||
expect(engine.current.penalized).toContain('p1')
|
||||
expect(engine.current.players.find((p) => p.id === 'p1')?.score).toBe(-100)
|
||||
})
|
||||
|
||||
it('аукцион по таймауту достаётся лидеру', () => {
|
||||
const { engine, clock } = setup()
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t2/1' }, { actor: p1 }))
|
||||
expectOk(engine.dispatch({ type: 'bet', amount: 100 }, { actor: p2 }))
|
||||
clock.value += 30_001
|
||||
expectOk(engine.dispatch({ type: 'tick' }, { actor: SYSTEM }))
|
||||
expect(engine.current.phase).toBe('answering')
|
||||
expect(engine.current.answerer).toBe('p2')
|
||||
expect(engine.current.stake).toBe(100)
|
||||
})
|
||||
})
|
||||
|
||||
describe('undo и идемпотентность', () => {
|
||||
it('откатывает последний шаг и сохраняет растущий seq', () => {
|
||||
const { engine } = setup()
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t1/0' }, { actor: p1 }))
|
||||
expectOk(engine.dispatch({ type: 'buzz' }, { actor: p1 }))
|
||||
expectOk(engine.dispatch({ type: 'judge', verdict: 'correct' }, { actor: HOST }))
|
||||
expect(engine.current.phase).toBe('reveal')
|
||||
const seqBefore = engine.current.seq
|
||||
|
||||
expectOk(engine.undo(HOST))
|
||||
|
||||
expect(engine.current.phase).toBe('answering')
|
||||
expect(engine.current.players.find((p) => p.id === 'p1')?.score).toBe(0)
|
||||
expect(engine.current.closed).not.toContain('r1/t1/0')
|
||||
expect(engine.current.seq).toBe(seqBefore + 1)
|
||||
})
|
||||
|
||||
it('не даёт откатывать игроку', () => {
|
||||
const { engine } = setup()
|
||||
expect(expectFail(engine.undo(p1))).toMatch(/только ведущий/)
|
||||
})
|
||||
|
||||
it('повторная команда с тем же cmdId не применяется дважды', () => {
|
||||
const { engine } = setup()
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t1/0' }, { actor: p1 }))
|
||||
const first = expectOk(engine.dispatch({ type: 'buzz' }, { actor: p1, cmdId: 'same' }))
|
||||
const second = expectOk(engine.dispatch({ type: 'buzz' }, { actor: p2, cmdId: 'same' }))
|
||||
expect(second.state).toBe(first.state)
|
||||
expect(engine.current.answerer).toBe('p1')
|
||||
expect(engine.current.buzzes).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('авторизация', () => {
|
||||
it('игрок не может выбрать клетку не в свой ход', () => {
|
||||
const { engine } = setup()
|
||||
expect(expectFail(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t1/0' }, { actor: p2 })))
|
||||
.toMatch(/другой игрок/)
|
||||
})
|
||||
|
||||
it('экран табло не управляет игрой', () => {
|
||||
const { engine } = setup()
|
||||
const board: Actor = { id: 'board', role: 'board' }
|
||||
expect(expectFail(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t1/0' }, { actor: board })))
|
||||
.toMatch(/не управляет/)
|
||||
expect(expectFail(engine.dispatch({ type: 'next' }, { actor: board }))).toMatch(/только ведущий/)
|
||||
})
|
||||
|
||||
it('игрок не может судить и менять очки', () => {
|
||||
const { engine } = setup()
|
||||
expect(expectFail(engine.dispatch({ type: 'adjustScore', playerId: 'p1', delta: 500 }, { actor: p1 })))
|
||||
.toMatch(/только ведущий/)
|
||||
expect(expectFail(engine.dispatch({ type: 'judge', verdict: 'correct' }, { actor: p1 })))
|
||||
.toMatch(/только ведущий/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('проекция по ролям', () => {
|
||||
it('не отдаёт правильный ответ на табло и телефоны до вскрытия', () => {
|
||||
const { engine } = setup()
|
||||
const pack = makePack()
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t1/0' }, { actor: p1 }))
|
||||
|
||||
const boardView = project(pack, engine.current, 'board')
|
||||
expect(JSON.stringify(boardView)).not.toContain('Ответ 100')
|
||||
expect(boardView.active?.question.text).toBe('Вопрос за 100')
|
||||
|
||||
const playerView = project(pack, engine.current, 'player', 'p1')
|
||||
expect(JSON.stringify(playerView)).not.toContain('Ответ 100')
|
||||
expect(playerView.you?.canBuzz).toBe(true)
|
||||
|
||||
// Только ведущему ответ доступен сразу — он по нему судит.
|
||||
const hostView = project(pack, engine.current, 'host')
|
||||
expect(hostView.active?.answer).toBe('Ответ 100')
|
||||
})
|
||||
|
||||
it('после вскрытия ответ появляется у всех', () => {
|
||||
const { engine } = setup()
|
||||
const pack = makePack()
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t1/0' }, { actor: p1 }))
|
||||
expectOk(engine.dispatch({ type: 'nominate', playerId: 'p2' }, { actor: HOST }))
|
||||
expectOk(engine.dispatch({ type: 'judge', verdict: 'skip' }, { actor: HOST }))
|
||||
|
||||
const boardView = project(pack, engine.current, 'board')
|
||||
expect(boardView.revealed?.answer).toBe('Ответ 100')
|
||||
})
|
||||
|
||||
it('прячет чужие ставки аукциона, но показывает свою', () => {
|
||||
const { engine } = setup()
|
||||
const pack = makePack()
|
||||
expectOk(engine.dispatch({ type: 'selectCell', cellKey: 'r1/t2/1' }, { actor: p1 }))
|
||||
expectOk(engine.dispatch({ type: 'bet', amount: 120 }, { actor: p1 }))
|
||||
|
||||
const viewOfP1 = project(pack, engine.current, 'player', 'p1')
|
||||
expect(viewOfP1.you?.bet).toBe(120)
|
||||
expect(viewOfP1.bets).toBeUndefined()
|
||||
|
||||
const viewOfP2 = project(pack, engine.current, 'player', 'p2')
|
||||
expect(viewOfP2.you?.bet).toBeUndefined()
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user