diff --git a/README.md b/README.md index bab017b..d325a83 100644 --- a/README.md +++ b/README.md @@ -260,12 +260,24 @@ npm run import -- вопросы.csv --id=novy-god | `novy-god-2027.json` | игра на вечер: 5 тем × 5 вопросов и финал | | `demo.json` | маленький, для проверки движка | -Сервер берёт пак, первый по алфавиту. Выбрать другой: +### Как переключаться между играми + +**В пульте.** В лобби под списком игроков есть блок «Какая игра?» — все паки +с диска, у текущего пометка «играем», у остальных кнопка «Выбрать». Переключение +мгновенное: табло и телефоны обновляются сами, игроки остаются, счёт обнуляется. + +**На странице импорта.** Раздел «Игры на диске» — то же самое, рядом с загрузкой. + +**На старте.** Сервер берёт пак, первый по алфавиту. Выбрать другой: ```powershell $env:QUIZ_PACK='novy-god-2027'; npm run dev ``` +Переключать можно только в лобби или на итогах: посреди партии открытые клетки +указывали бы в вопросы из другого пака. Если нужно сменить игру в разгар, пульт +попросит нажать «⟲ Заново». + Тесты проверяют **все** паки в `content/packs/`: схему и то, что каждый медиафайл действительно лежит на диске. Самый обидный баг вечера — вопрос с музыкой, у которого нет файла, поэтому он ловится на `npm test`. diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts index 3346489..68e713b 100644 --- a/packages/server/src/app.ts +++ b/packages/server/src/app.ts @@ -150,13 +150,24 @@ export async function buildApp(options: AppOptions): Promise { 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 { 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, diff --git a/packages/server/src/room.ts b/packages/server/src/room.ts index 36a9fef..aaa9dd1 100644 --- a/packages/server/src/room.ts +++ b/packages/server/src/room.ts @@ -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: [], diff --git a/packages/server/test/import.test.ts b/packages/server/test/import.test.ts index 8d086d5..63618a6 100644 --- a/packages/server/test/import.test.ts +++ b/packages/server/test/import.test.ts @@ -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 } - 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') }) diff --git a/packages/web/src/styles.css b/packages/web/src/styles.css index 5ebfea6..8e6f15f 100644 --- a/packages/web/src/styles.css +++ b/packages/web/src/styles.css @@ -1032,3 +1032,54 @@ a.ghost { color: #2a1f06; background: linear-gradient(180deg, #f1d288, #d8aa47); } + +/* ─── Выбор игры ─────────────────────────────────────────────────────── */ + +.pack-picker { + display: flex; + flex-direction: column; + gap: 0.4rem; + width: min(560px, 92vw); +} + +.pack-row { + display: flex; + align-items: center; + gap: 0.7rem; + padding: 0.55rem 0.8rem; + border-radius: 12px; + background: rgba(0, 0, 0, 0.2); + border: 1px solid rgba(255, 255, 255, 0.07); +} + +.pack-row.active { + border-color: var(--gold); + background: var(--gold-soft); +} + +.pack-info { + flex: 1; + display: flex; + flex-direction: column; + gap: 0.1rem; + text-align: left; + min-width: 0; +} + +.pack-info b { + font-size: 0.95rem; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.pack-info .note { + font-size: 0.72rem; + color: var(--muted); +} + +.pack-row .ghost { + flex: none; + padding: 0.4em 0.9em; + font-size: 0.85rem; +} diff --git a/packages/web/src/views/HostView.vue b/packages/web/src/views/HostView.vue index 22a6a86..a857dff 100644 --- a/packages/web/src/views/HostView.vue +++ b/packages/web/src/views/HostView.vue @@ -39,8 +39,18 @@ const QUESTION_PHASES = ['question', 'cat_nominate', 'auction', 'answering', 're const route = useRoute() const { say } = useToast() +interface PackChoice { + id: string + title: string + rounds: number + cells: number + current: boolean +} + const room = ref('') const fatal = ref('') +const packs = ref([]) +const switching = ref(false) const showAnswer = ref(false) const betDraft = ref>({}) const now = ref(Date.now()) @@ -72,6 +82,36 @@ const tags = computed(() => { return [] }) +async function loadPacks(): Promise { + try { + const response = await fetch('/api/packs') + if (!response.ok) return + const data = (await response.json()) as { packs?: PackChoice[] } + packs.value = data.packs ?? [] + } catch { + // Список не критичен: играть можно и без него. + } +} + +async function choosePack(id: string): Promise { + if (switching.value) return + switching.value = true + try { + const query = new URLSearchParams({ token: String(route.params.token ?? ''), id }) + const response = await fetch(`/api/packs/apply?${query.toString()}`, { method: 'POST' }) + const data = (await response.json()) as { ok: boolean; error?: string } + if (!data.ok) { + say(data.error ?? 'не удалось переключить игру') + return + } + await loadPacks() + } catch { + say('нет связи с сервером') + } finally { + switching.value = false + } +} + let timer: ReturnType | undefined onMounted(async () => { @@ -86,6 +126,7 @@ onMounted(async () => { return } game.connect({ role: 'host', room: room.value, token }) + void loadPacks() timer = setInterval(() => { now.value = Date.now() }, 200) @@ -179,6 +220,31 @@ function selectCell(key: string): void { {{ player.name }}

Пока никто не подключился

+ +
+

Какая игра?

+
+ + {{ pack.title }} + {{ pack.rounds }} р. · {{ pack.cells }} вопросов + + играем + +
+
+ diff --git a/packages/web/src/views/ImportView.vue b/packages/web/src/views/ImportView.vue index 3271ca6..c9a58ab 100644 --- a/packages/web/src/views/ImportView.vue +++ b/packages/web/src/views/ImportView.vue @@ -42,6 +42,7 @@ interface PackInfo { interface Info { packs: PackInfo[] + current: string mediaFolders: string[] sfx: Record sfxNames: string[] @@ -60,6 +61,12 @@ const result = ref(null) const errors = ref([]) const hasFile = computed(() => payload.value !== null) +const currentId = computed(() => info.value?.current ?? '') + +async function switchTo(id: string): Promise { + await applyPack(id) + await refreshInfo() +} async function refreshInfo(): Promise { try { @@ -258,13 +265,17 @@ async function send(dry: boolean): Promise {
-

Паки на диске

-
    -
  • +

    Игры на диске

    +
    + {{ pack.title }} {{ pack.id }} · {{ pack.rounds }} р. · {{ pack.cells }} вопросов -
  • -
+ + играем + +
diff --git a/scripts/smoke-packs.mjs b/scripts/smoke-packs.mjs new file mode 100644 index 0000000..66798c8 --- /dev/null +++ b/scripts/smoke-packs.mjs @@ -0,0 +1,81 @@ +/** + * Проверка переключения игр в пульте: список, кнопка «Выбрать», смена пака. + * + * Требует запущенного сервера с известным токеном. Запуск: + * $env:PORT='3100'; $env:QUIZ_ROOM='TEST'; $env:QUIZ_HOST_TOKEN='smoke-token'; npm start + * $env:QUIZ_URL='http://127.0.0.1:3100'; node scripts/smoke-packs.mjs + */ + +import puppeteer from 'puppeteer-core' + +const BASE = process.env.QUIZ_URL ?? 'http://127.0.0.1:3100' +const TOKEN = process.env.QUIZ_HOST_TOKEN ?? 'smoke-token' +const CHROME = + process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe' + +const browser = await puppeteer.launch({ + executablePath: CHROME, + headless: 'new', + args: ['--disable-gpu', '--no-first-run'], + defaultViewport: { width: 1280, height: 900 }, +}) + +const problems = [] +const page = await browser.newPage() +page.on('pageerror', (error) => problems.push(error.message)) + +/** Возвращает весь ответ: и список, и id текущей игры. */ +const packs = async () => await (await fetch(`${BASE}/api/packs`)).json() + +try { + console.log('1. открываю пульт') + await page.goto(`${BASE}/host/${TOKEN}`, { waitUntil: 'networkidle0' }) + await page.waitForSelector('.pack-picker', { timeout: 15000 }) + + const rows = await page.$$eval('.pack-row', (nodes) => + nodes.map((node) => node.textContent?.replace(/\s+/g, ' ').trim()), + ) + console.log(` игр в списке: ${rows.length}`) + if (rows.length < 2) throw new Error('в списке меньше двух игр — нечего переключать') + + const before = await packs() + const target = before.packs.find((pack) => !pack.current) + if (!target) throw new Error('нет игры, на которую можно переключиться') + console.log(` сейчас: ${before.packs.find((pack) => pack.current)?.title}`) + console.log(` переключаю на: ${target.title}`) + + console.log('2. жму «Выбрать»') + // Жмём кнопку в строке, у которой ещё нет пометки «играем». + const clicked = await page.evaluate(() => { + const rows = Array.from(document.querySelectorAll('.pack-row')) + const row = rows.find((node) => !node.classList.contains('active')) + const button = row?.querySelector('button') + if (!button) return false + button.click() + return true + }) + if (!clicked) throw new Error('кнопка «Выбрать» не найдена') + + await page.waitForFunction( + () => document.querySelector('.pack-row.active')?.textContent?.includes('играем'), + { timeout: 10000 }, + ) + + const after = await packs() + console.log(` стало: ${after.packs.find((pack) => pack.current)?.title}`) + if (after.current === before.current) throw new Error('пак не переключился') + + console.log('3. в лобби остались игроки и нулевой счёт') + const active = await page.$eval('.pack-row.active', (node) => node.textContent?.replace(/\s+/g, ' ')) + console.log(` активная строка: ${active?.trim()}`) + + if (problems.length > 0) { + console.error('\nОшибки на странице:') + for (const problem of problems) console.error(` - ${problem}`) + process.exitCode = 1 + } else { + console.log('\nOK: игры переключаются из пульта') + } +} finally { + await browser.close() +}