Страница импорта и звуковые эффекты из файлов

- метаданные пака (название, id, финал) читаются из самого CSV
- страница /import/<токен>: перетащить таблицу, проверить, сохранить
- пак применяется без перезапуска сервера, если партия не начата
- звуки берутся из content/sfx/, иначе используется синтез
- заголовок таблицы ищется по содержимому, а не по позиции
This commit is contained in:
oskarvitalii committed 2026-11-16 15:19:58 +07:00
1 parent 2f0263e59b
commit ea2d5d905c
21 files changed
+1529 -88

No files matched your search

+77 -28
View File
@@ -1,19 +1,24 @@
/**
* Звуки квиза, синтезированные на месте.
* Звуковые эффекты: файлы, а на случай их отсутствия — синтез.
*
* Ни одного mp3 в репозитории: звук собирается из осцилляторов. Причина не в
* экономии — на площадке нечему «не загрузиться», и папку с ассетами нельзя
* забыть скопировать на другой ноутбук.
* Положите в content/sfx/ файл с нужным именем (correct.mp3, buzz.wav, …) —
* сервер сам отдаст его как /sfx/…, и он заменит встроенный звук. Ничего
* настраивать не нужно: имя файла и есть настройка.
*
* Браузер не даёт звучать до действия пользователя, поэтому на табло есть
* кнопка включения: один клик при настройке — и дальше всё играет само.
* Синтез остаётся запасным вариантом, чтобы игра звучала и на чистом проекте.
*/
const STORAGE_KEY = 'quiz:sound'
export const SFX_NAMES = ['open', 'buzz', 'correct', 'wrong', 'tick', 'end'] as const
export type SfxName = (typeof SFX_NAMES)[number]
let context: AudioContext | null = null
let enabled = false
const files = new Map<SfxName, string>()
const players = new Map<SfxName, HTMLAudioElement>()
export function preferredSound(): boolean {
try {
return localStorage.getItem(STORAGE_KEY) === '1'
@@ -26,6 +31,34 @@ export function soundEnabled(): boolean {
return enabled
}
export function availableSfx(): SfxName[] {
return [...files.keys()]
}
/**
* Спрашивает у сервера, какие эффекты заменены файлами, и заранее их грузит.
* Ошибка сети не критична: останется синтез.
*/
export async function loadSfx(): Promise<void> {
try {
const response = await fetch('/api/sfx')
if (!response.ok) return
const data = (await response.json()) as { files?: Record<string, string> }
for (const name of SFX_NAMES) {
const url = data.files?.[name]
if (!url) continue
files.set(name, url)
const audio = new Audio()
audio.src = url
audio.preload = 'auto'
audio.volume = 0.85
players.set(name, audio)
}
} catch {
// Сервер мог быть ещё не готов — останется синтез.
}
}
export async function enableSound(): Promise<boolean> {
if (typeof window === 'undefined') return false
try {
@@ -48,6 +81,8 @@ export function disableSound(): void {
}
}
// ─── Синтез (запасной вариант) ─────────────────────────────────────────────
interface ToneOptions {
frequency: number
duration: number
@@ -58,7 +93,7 @@ interface ToneOptions {
}
function tone(options: ToneOptions): void {
if (!enabled || !context || context.state !== 'running') return
if (!context || context.state !== 'running') return
const start = context.currentTime + (options.delay ?? 0)
const oscillator = context.createOscillator()
@@ -81,32 +116,46 @@ function tone(options: ToneOptions): void {
oscillator.stop(start + options.duration + 0.03)
}
export const sfx = {
/** Открылась клетка. */
open(): void {
tone({ frequency: 520, sweepTo: 880, duration: 0.12, type: 'triangle', gain: 0.1 })
},
/** Кто-то нажал кнопку. */
buzz(): void {
tone({ frequency: 190, sweepTo: 120, duration: 0.16, type: 'square', gain: 0.12 })
},
/** Ответ верный. */
correct(): void {
const SYNTH: Record<SfxName, () => void> = {
open: () => tone({ frequency: 520, sweepTo: 880, duration: 0.12, type: 'triangle', gain: 0.1 }),
buzz: () => tone({ frequency: 190, sweepTo: 120, duration: 0.16, type: 'square', gain: 0.12 }),
correct: () => {
tone({ frequency: 660, duration: 0.16, type: 'sine', gain: 0.16 })
tone({ frequency: 990, duration: 0.24, type: 'sine', gain: 0.14, delay: 0.12 })
},
/** Ответ неверный или время вышло. */
wrong(): void {
tone({ frequency: 240, sweepTo: 110, duration: 0.38, type: 'sawtooth', gain: 0.1 })
},
/** Последние секунды. */
tick(): void {
tone({ frequency: 1200, duration: 0.045, type: 'sine', gain: 0.05 })
},
/** Раунд или партия закончились. */
end(): void {
wrong: () => tone({ frequency: 240, sweepTo: 110, duration: 0.38, type: 'sawtooth', gain: 0.1 }),
tick: () => tone({ frequency: 1200, duration: 0.045, type: 'sine', gain: 0.05 }),
end: () => {
for (const [index, frequency] of [523, 659, 784].entries()) {
tone({ frequency, duration: 0.5, type: 'sine', gain: 0.1, delay: index * 0.09 })
}
},
}
// ─── Воспроизведение ───────────────────────────────────────────────────────
function play(name: SfxName): void {
if (!enabled) return
const player = players.get(name)
if (player) {
try {
player.currentTime = 0
void player.play()
return
} catch {
// Файл не проигрался — не повод молчать, сыграем синтезом.
}
}
SYNTH[name]()
}
export const sfx = {
open: (): void => play('open'),
buzz: (): void => play('buzz'),
correct: (): void => play('correct'),
wrong: (): void => play('wrong'),
tick: (): void => play('tick'),
end: (): void => play('end'),
}
+2
View File
@@ -2,6 +2,7 @@ import { createRouter, createWebHistory } from 'vue-router'
import BoardView from './views/BoardView.vue'
import HomeView from './views/HomeView.vue'
import HostView from './views/HostView.vue'
import ImportView from './views/ImportView.vue'
import PlayerView from './views/PlayerView.vue'
export const router = createRouter({
@@ -10,6 +11,7 @@ export const router = createRouter({
{ path: '/', name: 'home', component: HomeView },
{ path: '/board', name: 'board', component: BoardView },
{ path: '/host/:token', name: 'host', component: HostView },
{ path: '/import/:token', name: 'import', component: ImportView },
{ path: '/play', name: 'play', component: PlayerView },
{ path: '/:pathMatch(.*)*', redirect: '/' },
],
+145
View File
@@ -874,3 +874,148 @@ input:focus {
transform: none;
}
}
/* ─── Страница импорта ───────────────────────────────────────────────── */
.import {
flex: 1;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
gap: clamp(0.7rem, 1.6vmin, 1.2rem);
align-content: start;
padding-bottom: 2rem;
}
.import-card {
display: flex;
flex-direction: column;
gap: 0.6rem;
padding: clamp(0.9rem, 2vmin, 1.4rem);
border-radius: var(--radius);
background: var(--panel);
border: 1px solid rgba(255, 255, 255, 0.07);
}
.import-card .note {
max-width: none;
text-align: left;
}
.import-card code {
background: rgba(0, 0, 0, 0.32);
border-radius: 6px;
padding: 0.1em 0.4em;
font-size: 0.9em;
color: var(--gold);
word-break: break-word;
}
.bad-card {
border-color: rgba(226, 103, 95, 0.45);
background: rgba(226, 103, 95, 0.07);
}
.ok-card {
border-color: rgba(72, 185, 138, 0.45);
background: rgba(72, 185, 138, 0.07);
}
.import-title {
margin: 0;
font-size: clamp(1.1rem, 2.6vmin, 1.6rem);
font-weight: 650;
color: var(--gold);
}
.drop {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 0.35rem;
min-height: 120px;
padding: 1rem;
border-radius: var(--radius);
border: 2px dashed rgba(233, 196, 106, 0.35);
background: rgba(0, 0, 0, 0.18);
cursor: pointer;
text-align: center;
transition: border-color 0.15s, background 0.15s;
}
.drop:hover,
.drop.over {
border-color: var(--gold);
background: var(--gold-soft);
}
.drop.filled {
border-style: solid;
}
.drop-title {
font-size: clamp(0.95rem, 2vmin, 1.15rem);
font-weight: 600;
word-break: break-all;
}
.drop-hint {
font-size: 0.78rem;
color: var(--muted);
}
.error-list {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 0.4rem;
font-size: 0.88rem;
}
.error-list li {
display: flex;
gap: 0.6rem;
align-items: baseline;
}
.line-no {
flex: none;
color: var(--bad);
font-variant-numeric: tabular-nums;
font-size: 0.78rem;
min-width: 4.6rem;
}
.warn-block {
margin-top: 0.4rem;
padding-top: 0.5rem;
border-top: 1px solid rgba(255, 255, 255, 0.08);
}
.pack-list {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 0.45rem;
font-size: 0.88rem;
}
.pack-list li {
display: flex;
flex-direction: column;
gap: 0.1rem;
}
.pack-list .note {
font-size: 0.76rem;
color: var(--muted);
}
a.ghost {
text-decoration: none;
display: inline-block;
}
+3 -1
View File
@@ -14,7 +14,7 @@ import BoardGrid from '../components/BoardGrid.vue'
import Countdown from '../components/Countdown.vue'
import QuestionMedia from '../components/QuestionMedia.vue'
import ScoreBar from '../components/ScoreBar.vue'
import { disableSound, enableSound, preferredSound, sfx } from '../audio/sfx'
import { disableSound, enableSound, loadSfx, preferredSound, sfx } from '../audio/sfx'
import { game } from '../net/game'
import { rememberRoom, resolveRoom } from '../net/room'
@@ -85,6 +85,8 @@ onMounted(async () => {
}
rememberRoom(room.value)
game.connect({ role: 'board', room: room.value })
// Файловые звуки из content/sfx подхватываются до первого вопроса.
void loadSfx()
timer = setInterval(() => {
now.value = Date.now()
}, 200)
+3
View File
@@ -147,6 +147,9 @@ function selectCell(key: string): void {
<span class="spacer" />
<span v-if="room" class="room-tag">комната {{ room }}</span>
<span v-if="state" class="phase-badge">{{ label }}</span>
<RouterLink class="ghost" :to="`/import/${String(route.params.token ?? '')}`" title="Загрузить вопросы из таблицы">
⇪ Импорт
</RouterLink>
<button v-if="phase !== 'lobby'" class="ghost" title="Начать партию заново" @click="resetGame">
⟲ Заново
</button>
+288
View File
@@ -0,0 +1,288 @@
<script setup lang="ts">
/**
* Загрузка пака из таблицы.
*
* Сценарий: положить медиа в content/media/<id-пака>/, подготовить CSV с
* названием игры и вопросами, перетащить файл сюда. Всё остальное — здесь.
*
* Страница требует токен ведущего: она пишет файлы на сервер, и открывать её
* кому попало нельзя.
*/
import { computed, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
interface ImportError {
line: number
message: string
}
interface ImportSuccess {
ok: true
pack: { id: string; title: string; rounds: unknown[] }
stats: { rounds: number; themes: number; cells: number }
encoding: string
missingMedia: string[]
written: boolean
file?: string
replaced: boolean
}
interface ImportFailure {
ok: false
errors: ImportError[]
}
interface PackInfo {
id: string
title: string
rounds: number
cells: number
}
interface Info {
packs: PackInfo[]
mediaFolders: string[]
sfx: Record<string, string>
sfxNames: string[]
}
const route = useRoute()
const token = computed(() => String(route.params.token ?? ''))
const info = ref<Info | null>(null)
const fatal = ref('')
const fileName = ref('')
const payload = ref<ArrayBuffer | null>(null)
const busy = ref(false)
const dragging = ref(false)
const result = ref<ImportSuccess | null>(null)
const errors = ref<ImportError[]>([])
const hasFile = computed(() => payload.value !== null)
async function refreshInfo(): Promise<void> {
try {
const response = await fetch(`/api/import/info?token=${encodeURIComponent(token.value)}`)
if (response.status === 403) {
fatal.value = 'Неверный токен ведущего'
return
}
if (!response.ok) {
fatal.value = 'Сервер не ответил'
return
}
info.value = (await response.json()) as Info
} catch {
fatal.value = 'Нет связи с сервером'
}
}
onMounted(refreshInfo)
function reset(): void {
result.value = null
errors.value = []
}
async function takeFile(file: File | undefined): Promise<void> {
if (!file) return
reset()
fileName.value = file.name
payload.value = await file.arrayBuffer()
}
function onDrop(event: DragEvent): void {
dragging.value = false
const file = event.dataTransfer?.files?.[0]
void takeFile(file)
}
function onPick(event: Event): void {
const input = event.target as HTMLInputElement
void takeFile(input.files?.[0])
}
const applied = ref('')
const applyError = ref('')
async function applyPack(id: string): Promise<void> {
applied.value = ''
applyError.value = ''
try {
const response = await fetch(
`/api/packs/apply?token=${encodeURIComponent(token.value)}&id=${encodeURIComponent(id)}`,
{ method: 'POST' },
)
const data = (await response.json()) as { ok: boolean; error?: string }
if (data.ok) applied.value = id
else applyError.value = data.error ?? 'не удалось применить пак'
} catch {
applyError.value = 'не удалось применить пак'
}
}
async function send(dry: boolean): Promise<void> {
if (!payload.value || busy.value) return
busy.value = true
reset()
try {
const query = new URLSearchParams({ token: token.value })
if (dry) query.set('dry', '1')
const response = await fetch(`/api/import?${query.toString()}`, {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: payload.value,
})
const data = (await response.json()) as ImportSuccess | ImportFailure | { error: string }
if (!response.ok || !('ok' in data)) {
errors.value = [{ line: 0, message: 'error' in data ? data.error : 'сервер отказал' }]
return
}
if (data.ok) {
result.value = data
if (!dry) {
// Сразу берём пак в игру: сервер разрешает это только в лобби.
await applyPack(data.pack.id)
await refreshInfo()
}
} else {
errors.value = data.errors
}
} catch {
errors.value = [{ line: 0, message: 'не удалось отправить файл' }]
} finally {
busy.value = false
}
}
</script>
<template>
<div class="shell">
<header class="topbar">
<h1>Импорт из таблицы</h1>
<span class="spacer" />
<RouterLink class="ghost" :to="`/host/${token}`">← К пульту</RouterLink>
</header>
<div v-if="fatal" class="fatal">
<h2>Импорт недоступен</h2>
<p>{{ fatal }}</p>
</div>
<main v-else class="import">
<section class="import-card">
<p class="kicker">1. Подготовьте медиа</p>
<p class="note">
Положите картинки и музыку в
<code>content/media/&lt;id-пака&gt;/</code>. В таблице достаточно имени файла —
путь допишется сам.
</p>
<p v-if="info?.mediaFolders.length" class="note">
Уже есть:
<span v-for="folder in info.mediaFolders" :key="folder" class="tag">{{ folder }}</span>
</p>
<p v-else class="note">Папок с медиа пока нет</p>
</section>
<section class="import-card">
<p class="kicker">2. Перетащите CSV</p>
<label
class="drop"
:class="{ over: dragging, filled: hasFile }"
@dragover.prevent="dragging = true"
@dragleave.prevent="dragging = false"
@drop.prevent="onDrop"
>
<input type="file" accept=".csv,.tsv,.txt,text/csv" hidden @change="onPick" />
<span v-if="!hasFile" class="drop-title">Файл таблицы</span>
<span v-else class="drop-title">{{ fileName }}</span>
<span class="drop-hint">
{{ hasFile ? 'Можно выбрать другой файл' : 'CSV или TSV, UTF-8 или Windows-1251' }}
</span>
</label>
<p class="note">
Колонки: <code>Тема</code>, <code>Стоимость</code>, <code>Вопрос</code>,
<code>Ответ</code>, по желанию <code>Раунд</code>, <code>Комментарий</code>,
<code>Тип</code>, <code>Медиа</code>. Название игры и финальный вопрос —
строками выше заголовка: <code>Название;Новогодний квиз 2027</code>.
</p>
<div class="chips">
<button class="ghost" :disabled="!hasFile || busy" @click="send(true)">
Проверить
</button>
<button class="primary" :disabled="!hasFile || busy" @click="send(false)">
{{ busy ? 'Отправляю…' : 'Сохранить пак' }}
</button>
</div>
</section>
<section v-if="errors.length" class="import-card bad-card">
<p class="kicker">Ошибки в таблице</p>
<ul class="error-list">
<li v-for="(error, index) in errors" :key="index">
<span v-if="error.line > 0" class="line-no">строка {{ error.line }}</span>
<span v-else class="line-no">пак</span>
{{ error.message }}
</li>
</ul>
</section>
<section v-if="result" class="import-card ok-card">
<p class="kicker">{{ result.written ? 'Пак сохранён' : 'Проверка пройдена' }}</p>
<p class="import-title">{{ result.pack.title }}</p>
<p class="note">
id: <code>{{ result.pack.id }}</code> · раундов {{ result.stats.rounds }} · тем
{{ result.stats.themes }} · клеток {{ result.stats.cells }} · кодировка
{{ result.encoding }}
</p>
<p v-if="result.replaced && result.written" class="note">
Пак с таким id уже был — он перезаписан.
</p>
<div v-if="result.missingMedia.length" class="warn-block">
<p class="kicker">Медиа не найдено на диске</p>
<p v-for="source in result.missingMedia" :key="source" class="warn">{{ source }}</p>
<p class="note">Вопрос сыграет без файла — проверьте папку content/media.</p>
</div>
<p v-if="applied" class="note">
Пак уже в игре — можно открывать табло. Если партия была начата, сервер
попросит нажать «⟲ Заново».
</p>
<p v-if="applyError" class="warn">{{ applyError }}</p>
</section>
<section v-if="info?.packs.length" class="import-card">
<p class="kicker">Паки на диске</p>
<ul class="pack-list">
<li v-for="pack in info.packs" :key="pack.id">
<b>{{ pack.title }}</b>
<span class="note">{{ pack.id }} · {{ pack.rounds }} р. · {{ pack.cells }} вопросов</span>
</li>
</ul>
</section>
<section class="import-card">
<p class="kicker">Звуковые эффекты</p>
<p class="note">
Сейчас из файлов:
<template v-if="Object.keys(info?.sfx ?? {}).length">
<span v-for="(url, name) in info?.sfx" :key="name" class="tag">{{ name }}</span>
</template>
<template v-else>ни одного, играет встроенный синтез</template>
</p>
<p class="note">
Положите файл в <code>content/sfx/</code> с именем
<code>correct.mp3</code>, <code>wrong.wav</code>, <code>buzz.mp3</code>,
<code>open.mp3</code>, <code>tick.mp3</code> или <code>end.mp3</code> — он
заменит встроенный звук.
</p>
</section>
</main>
</div>
</template>