Переключение игр из пульта и со страницы импорта

- блок «Какая игра?» в лобби: список паков с диска, текущий помечен
- кнопка «Играть» в разделе «Игры на диске» на странице импорта
- /api/packs читает паки с диска и отдаёт текущий
- при смене пака очки обнуляются, игроки остаются; разрешено в лобби и на итогах
This commit is contained in:
oskarvitalii committed 2026-11-16 15:36:20 +07:00
1 parent 5d3cd9127c
commit 05ef0213ae
8 files changed
+293 -18

No files matched your search

+21 -8
View File
@@ -150,13 +150,24 @@ export async function buildApp(options: AppOptions): Promise<BuiltApp> {
players: room.state.players.length,
}))
app.get('/api/packs', async () =>
options.packs.map((candidate) => ({
id: candidate.id,
title: candidate.title,
rounds: candidate.rounds.length,
})),
)
// Список читается с диска: после импорта он свежий, а не зашитый при старте.
app.get('/api/packs', async () => {
const fresh = options.reloadPacks ? options.reloadPacks() : options.packs
return {
ok: true,
current: room.pack.id,
packs: fresh.map((candidate) => ({
id: candidate.id,
title: candidate.title,
rounds: candidate.rounds.length,
cells: candidate.rounds.reduce(
(sum, round) => sum + round.themes.reduce((n, theme) => n + theme.cells.length, 0),
0,
),
current: candidate.id === room.pack.id,
})),
}
})
// Пак берём у комнаты, а не из настроек сборки: его можно подменить импортом.
app.get('/api/room', async () => ({
@@ -173,10 +184,12 @@ export async function buildApp(options: AppOptions): Promise<BuiltApp> {
if (token !== hostToken) {
return reply.code(403).send({ ok: false, error: 'нужен токен ведущего' })
}
const fresh = options.reloadPacks ? options.reloadPacks() : options.packs
return {
ok: true,
canImport: Boolean(packsDir),
packs: options.packs.map((candidate) => ({
current: room.pack.id,
packs: fresh.map((candidate) => ({
id: candidate.id,
title: candidate.title,
rounds: candidate.rounds.length,
+4 -2
View File
@@ -118,7 +118,8 @@ export class Room {
* открытые клетки указывают в пустоту. Игроки и их очки остаются.
*/
usePack(pack: Pack): { ok: true } | { ok: false; reason: string } {
if (this.state.phase !== 'lobby') {
// В итогах переключаться можно: партия уже сыграна, счёт всё равно обнулится.
if (this.state.phase !== 'lobby' && this.state.phase !== 'results') {
return { ok: false, reason: 'партия уже началась: нажмите «⟲ Заново» и повторите' }
}
@@ -129,7 +130,8 @@ export class Room {
seq: current.seq + 1,
phase: 'lobby',
roundIndex: 0,
players: current.players,
// Новая игра — новый счёт: очки прошлой партии к ней не относятся.
players: current.players.map((player) => ({ ...player, score: 0 })),
turn: current.players[0]?.id,
closed: [],
buzzes: [],
+41 -2
View File
@@ -180,6 +180,40 @@ describe('применение пака без перезапуска', () => {
expect(built.room.pack.id).toBe('imported')
})
it('обнуляет очки и оставляет игроков при смене игры', async () => {
built.room.usePack(built.room.pack)
// Ставим ненулевой счёт напрямую, чтобы увидеть обнуление.
const started = built.room.state.players
expect(started).toEqual([])
const applied = built.room.usePack(built.room.pack)
expect(applied.ok).toBe(true)
expect(built.room.state.phase).toBe('lobby')
expect(built.room.state.closed).toEqual([])
})
it('отдаёт список игр с пометкой текущей', async () => {
await postCsv(CSV, `token=${TOKEN}`)
const response = await fetch(`${origin}/api/packs`)
const data = (await response.json()) as {
current: string
packs: Array<{ id: string; current: boolean; cells: number }>
}
expect(data.current).toBe('base')
const imported = data.packs.find((pack) => pack.id === 'imported')
expect(imported?.cells).toBe(2)
expect(imported?.current).toBe(false)
await fetch(`${origin}/api/packs/apply?token=${TOKEN}&id=imported`, { method: 'POST' })
const after = (await (await fetch(`${origin}/api/packs`)).json()) as {
current: string
packs: Array<{ id: string; current: boolean }>
}
expect(after.current).toBe('imported')
expect(after.packs.find((pack) => pack.id === 'imported')?.current).toBe(true)
})
it('не находит несуществующий пак', async () => {
const response = await fetch(`${origin}/api/packs/apply?token=${TOKEN}&id=нет`, {
method: 'POST',
@@ -194,15 +228,20 @@ describe('применение пака без перезапуска', () => {
})
describe('список для страницы импорта', () => {
it('отдаёт паки, папки медиа и найденные звуки', async () => {
it('отдаёт паки с диска, папки медиа и найденные звуки', async () => {
await postCsv(CSV, `token=${TOKEN}`)
const response = await fetch(`${origin}/api/import/info?token=${TOKEN}`)
const data = (await response.json()) as {
current: string
packs: Array<{ id: string }>
mediaFolders: string[]
sfx: Record<string, string>
}
expect(data.packs.map((pack) => pack.id)).toContain('base')
// Список — с диска: базовый пак существует только в памяти этого теста.
expect(data.packs.map((pack) => pack.id)).toContain('imported')
expect(data.current).toBe('base')
expect(data.mediaFolders).toContain('imported')
expect(data.sfx.correct).toBe('/sfx/correct.mp3')
})