Новогодний квиз: ядро, сервер и три экрана
- ядро: контент, reducer всех фаз, undo, проекции по ролям - сервер: комнаты, сокеты, таймеры, раздача интерфейса и медиа - интерфейс: табло, пульт ведущего, телефон игрока - контент: пак 5x5 с финалом и демо-пак с рабочим аудио - 57 тестов и e2e на трёх вкладках
This commit is contained in:
commit
89eeea4855
54 files changed
+12010
No files matched your search
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Диагностика страницы: открывает адрес, печатает ошибки консоли и видимый текст.
|
||||
* Запуск: node scripts/debug-page.mjs /board
|
||||
*/
|
||||
|
||||
import puppeteer from 'puppeteer-core'
|
||||
|
||||
const path = process.argv[2] ?? '/'
|
||||
const base = process.env.QUIZ_URL ?? 'http://127.0.0.1:5173'
|
||||
|
||||
const browser = await puppeteer.launch({
|
||||
executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe',
|
||||
headless: 'new',
|
||||
args: ['--disable-gpu', '--no-first-run'],
|
||||
defaultViewport: { width: 1280, height: 800 },
|
||||
})
|
||||
|
||||
const page = await browser.newPage()
|
||||
page.on('console', (message) => console.log(`[${message.type()}] ${message.text()}`))
|
||||
page.on('pageerror', (error) => console.log(`[pageerror] ${error.message}`))
|
||||
page.on('requestfailed', (request) =>
|
||||
console.log(`[requestfailed] ${request.url()} ${request.failure()?.errorText}`),
|
||||
)
|
||||
|
||||
await page.goto(`${base}${path}`, { waitUntil: 'networkidle0' })
|
||||
await new Promise((resolve) => setTimeout(resolve, 1500))
|
||||
|
||||
console.log('--- видимый текст ---')
|
||||
console.log(await page.evaluate(() => document.body.innerText.slice(0, 800)))
|
||||
|
||||
await browser.close()
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Генератор короткой мелодии в WAV.
|
||||
*
|
||||
* Нужен, чтобы музыкальный вопрос работал «из коробки»: в репозитории лежит
|
||||
* файл, а не ссылка на файл, которого нет. Замените его своей записью —
|
||||
* формат и имя значения не имеют, важна строка media.src в паке.
|
||||
*
|
||||
* Запуск: node scripts/make-audio.mjs
|
||||
*/
|
||||
|
||||
import { writeFileSync, mkdirSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const SAMPLE_RATE = 22050
|
||||
const OUT = fileURLToPath(new URL('../content/media/demo/jingle-bells.wav', import.meta.url))
|
||||
|
||||
const NOTES = {
|
||||
C4: 261.63,
|
||||
D4: 293.66,
|
||||
E4: 329.63,
|
||||
F4: 349.23,
|
||||
G4: 392.0,
|
||||
A4: 440.0,
|
||||
B4: 493.88,
|
||||
C5: 523.25,
|
||||
}
|
||||
|
||||
const BEAT = 0.28
|
||||
|
||||
/** «Jingle Bells» — мелодия в общественном достоянии, первые две фразы. */
|
||||
const MELODY = [
|
||||
['E4', 1], ['E4', 1], ['E4', 2],
|
||||
['E4', 1], ['E4', 1], ['E4', 2],
|
||||
['E4', 1], ['G4', 1], ['C4', 1], ['D4', 1], ['E4', 4],
|
||||
['F4', 1], ['F4', 1], ['F4', 1], ['F4', 1],
|
||||
['F4', 1], ['E4', 1], ['E4', 1], ['E4', 0.5], ['E4', 0.5],
|
||||
['E4', 1], ['D4', 1], ['D4', 1], ['E4', 1], ['D4', 2], ['G4', 2],
|
||||
]
|
||||
|
||||
const samples = []
|
||||
|
||||
for (const [note, beats] of MELODY) {
|
||||
const frequency = NOTES[note]
|
||||
const duration = beats * BEAT
|
||||
const total = Math.floor(duration * SAMPLE_RATE)
|
||||
const attack = Math.floor(0.01 * SAMPLE_RATE)
|
||||
const release = Math.floor(0.06 * SAMPLE_RATE)
|
||||
|
||||
for (let index = 0; index < total; index += 1) {
|
||||
// Простая огибающая: без неё на стыках нот слышны щелчки.
|
||||
let envelope = 1
|
||||
if (index < attack) envelope = index / attack
|
||||
else if (index > total - release) envelope = Math.max(0, (total - index) / release)
|
||||
|
||||
const time = index / SAMPLE_RATE
|
||||
const wave =
|
||||
Math.sin(2 * Math.PI * frequency * time) * 0.6 +
|
||||
Math.sin(2 * Math.PI * frequency * 2 * time) * 0.25 +
|
||||
Math.sin(2 * Math.PI * frequency * 3 * time) * 0.1
|
||||
|
||||
samples.push(wave * envelope * 0.35)
|
||||
}
|
||||
|
||||
// Короткая пауза между нотами.
|
||||
const gap = Math.floor(0.01 * SAMPLE_RATE)
|
||||
for (let index = 0; index < gap; index += 1) samples.push(0)
|
||||
}
|
||||
|
||||
const dataBytes = samples.length * 2
|
||||
const buffer = Buffer.alloc(44 + dataBytes)
|
||||
|
||||
buffer.write('RIFF', 0)
|
||||
buffer.writeUInt32LE(36 + dataBytes, 4)
|
||||
buffer.write('WAVE', 8)
|
||||
buffer.write('fmt ', 12)
|
||||
buffer.writeUInt32LE(16, 16)
|
||||
buffer.writeUInt16LE(1, 20) // PCM
|
||||
buffer.writeUInt16LE(1, 22) // моно
|
||||
buffer.writeUInt32LE(SAMPLE_RATE, 24)
|
||||
buffer.writeUInt32LE(SAMPLE_RATE * 2, 28)
|
||||
buffer.writeUInt16LE(2, 32)
|
||||
buffer.writeUInt16LE(16, 34)
|
||||
buffer.write('data', 36)
|
||||
buffer.writeUInt32LE(dataBytes, 40)
|
||||
|
||||
samples.forEach((sample, index) => {
|
||||
const clamped = Math.max(-1, Math.min(1, sample))
|
||||
buffer.writeInt16LE(Math.round(clamped * 32767), 44 + index * 2)
|
||||
})
|
||||
|
||||
mkdirSync(fileURLToPath(new URL('../content/media/demo/', import.meta.url)), { recursive: true })
|
||||
writeFileSync(OUT, buffer)
|
||||
|
||||
const seconds = (samples.length / SAMPLE_RATE).toFixed(1)
|
||||
console.log(`готово: ${OUT} (${seconds} с, ${Math.round(buffer.length / 1024)} КБ)`)
|
||||
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* Дымовой прогон игры на трёх экранах.
|
||||
*
|
||||
* Открывает в одном браузере три вкладки — табло, телефон игрока и пульт —
|
||||
* и проходит партию до первого набранного очка. Это проверка не вёрстки,
|
||||
* а связки: сокеты, роли, изоляция ответа и подсчёт.
|
||||
*
|
||||
* Требует запущенного `npm run dev` и фиксированных комнаты и токена:
|
||||
* QUIZ_ROOM=TEST QUIZ_HOST_TOKEN=smoke-token npm run dev
|
||||
*
|
||||
* Запуск: node scripts/smoke.mjs
|
||||
*/
|
||||
|
||||
import { mkdirSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import puppeteer from 'puppeteer-core'
|
||||
|
||||
const BASE = process.env.QUIZ_URL ?? 'http://127.0.0.1:5173'
|
||||
const ROOM = process.env.QUIZ_ROOM ?? 'TEST'
|
||||
const TOKEN = process.env.QUIZ_HOST_TOKEN ?? 'smoke-token'
|
||||
const OUT = fileURLToPath(new URL('../.screenshots/', import.meta.url))
|
||||
const CHROME =
|
||||
process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe'
|
||||
|
||||
mkdirSync(OUT, { recursive: true })
|
||||
|
||||
const browser = await puppeteer.launch({
|
||||
executablePath: CHROME,
|
||||
headless: 'new',
|
||||
args: ['--disable-gpu', '--no-first-run', '--no-default-browser-check'],
|
||||
defaultViewport: { width: 1440, height: 900 },
|
||||
protocolTimeout: 60_000,
|
||||
})
|
||||
|
||||
const problems = []
|
||||
|
||||
function watch(page, label) {
|
||||
page.on('pageerror', (error) => problems.push(`${label}: ${error.message}`))
|
||||
page.on('console', (message) => {
|
||||
if (message.type() === 'error') problems.push(`${label}: ${message.text()}`)
|
||||
})
|
||||
return page
|
||||
}
|
||||
|
||||
async function shot(page, name) {
|
||||
await page.screenshot({ path: `${OUT}${name}.png` })
|
||||
console.log(` снимок: ${name}.png`)
|
||||
}
|
||||
|
||||
async function newPage(path, label, viewport) {
|
||||
const page = watch(await browser.newPage(), label)
|
||||
await page.setViewport(viewport ?? { width: 1440, height: 900 })
|
||||
await page.goto(`${BASE}${path}`, { waitUntil: 'networkidle0' })
|
||||
return page
|
||||
}
|
||||
|
||||
// Chrome «замораживает» фоновые вкладки, и вызовы к ним по CDP повисают.
|
||||
// Поэтому перед работой с экраном его нужно вывести вперёд.
|
||||
async function focus(page) {
|
||||
await page.bringToFront()
|
||||
}
|
||||
|
||||
const phone = { width: 390, height: 844, isMobile: true, hasTouch: true }
|
||||
|
||||
try {
|
||||
console.log('1. пульт: чистое лобби')
|
||||
const host = await newPage(`/host/${TOKEN}`, 'пульт')
|
||||
await focus(host)
|
||||
host.on('dialog', (dialog) => dialog.accept())
|
||||
await host.waitForSelector('.topbar', { timeout: 15000 })
|
||||
|
||||
// Сервер держит партию в памяти: если прошлый прогон не дошёл до конца,
|
||||
// обнуляем её, иначе табло откроется не в лобби.
|
||||
const reset = await host.evaluate(() => {
|
||||
const button = Array.from(document.querySelectorAll('button')).find((node) =>
|
||||
node.textContent?.includes('Заново'),
|
||||
)
|
||||
if (!button) return false
|
||||
button.click()
|
||||
return true
|
||||
})
|
||||
if (reset) {
|
||||
console.log(' сброс прошлой партии')
|
||||
await host.waitForSelector('.primary.big', { timeout: 15000 })
|
||||
}
|
||||
|
||||
console.log('2. табло: лобби с QR')
|
||||
const board = await newPage('/board', 'табло')
|
||||
await focus(board)
|
||||
await board.waitForSelector('.qr', { timeout: 15000 })
|
||||
await shot(board, '10-board-lobby')
|
||||
|
||||
console.log('3. телефон: вход по коду комнаты')
|
||||
const player = await newPage(`/play?room=${ROOM}`, 'телефон', phone)
|
||||
await focus(player)
|
||||
await player.waitForSelector('.name-input', { timeout: 15000 })
|
||||
await player.type('.name-input', 'Аня')
|
||||
await player.click('button.primary.big')
|
||||
await player.waitForSelector('.player-stage', { timeout: 15000 })
|
||||
await shot(player, '11-player-lobby')
|
||||
|
||||
console.log('4. пульт видит игрока')
|
||||
await focus(host)
|
||||
await host.waitForSelector('.chip', { timeout: 15000 })
|
||||
|
||||
console.log('5. старт игры')
|
||||
await focus(host)
|
||||
await host.click('button.primary.big')
|
||||
await host.waitForSelector('.round-title')
|
||||
await host.click('button.primary.big')
|
||||
await host.waitForSelector('.board')
|
||||
await focus(board)
|
||||
await board.waitForSelector('.board')
|
||||
await shot(host, '12-host-board')
|
||||
|
||||
console.log('6. вопрос')
|
||||
await focus(host)
|
||||
await host.click('.cell:not(.closed)')
|
||||
await host.waitForSelector('.question-text')
|
||||
await focus(board)
|
||||
await board.waitForSelector('.question-text')
|
||||
|
||||
// Главная проверка изоляции: на табло ответа быть не должно.
|
||||
const leak = await board.$('.answer')
|
||||
if (leak) throw new Error('табло получило правильный ответ до вскрытия')
|
||||
await shot(board, '13-board-question')
|
||||
|
||||
console.log('7. игрок нажимает')
|
||||
await focus(player)
|
||||
await player.waitForSelector('.buzz', { timeout: 15000 })
|
||||
await shot(player, '14-player-buzz')
|
||||
await player.click('.buzz')
|
||||
await focus(host)
|
||||
await host.waitForSelector('.actions .ok', { timeout: 15000 })
|
||||
await focus(player)
|
||||
await player.waitForSelector('.player-block')
|
||||
|
||||
console.log('8. ведущий судит: верно')
|
||||
await focus(host)
|
||||
await host.click('.actions .ok')
|
||||
await host.waitForSelector('.answer')
|
||||
await focus(board)
|
||||
await board.waitForSelector('.answer', { timeout: 15000 })
|
||||
await shot(board, '15-board-reveal')
|
||||
|
||||
await focus(host)
|
||||
const scores = await host.$$eval('.score-chip', (nodes) =>
|
||||
nodes.map((node) => node.textContent?.replace(/\s+/g, ' ').trim()),
|
||||
)
|
||||
console.log(` счёт: ${scores.join(' | ')}`)
|
||||
if (!scores.some((text) => /100/.test(text ?? ''))) {
|
||||
throw new Error('очки не начислились')
|
||||
}
|
||||
|
||||
await focus(player)
|
||||
const playerScore = await player.$eval('.player-score', (node) => node.textContent?.trim())
|
||||
console.log(` очки на телефоне: ${playerScore}`)
|
||||
if (playerScore !== '100') throw new Error(`на телефоне ${playerScore}, ожидалось 100`)
|
||||
await shot(player, '16-player-reveal')
|
||||
|
||||
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()
|
||||
}
|
||||
Reference in new issue
Block a user