feat: add bark battle browser prototype
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -383,17 +383,17 @@
|
||||
| 结算后点击再来一局重置本局状态 | application/component | `src/games/bark-battle/application/BarkBattleController.test.ts`, `src/games/bark-battle/ui/BarkBattleResultPanel.test.tsx` | planned |
|
||||
| 结算后返回玩法入口 | integration/smoke | `src/games/bark-battle/application/BarkBattleController.test.ts`, Playwright 或人工 smoke 清单 | planned |
|
||||
| 移动端进入对战页面时核心元素可见 | component/visual/smoke | `src/games/bark-battle/ui/BarkBattleHud.test.tsx`, Playwright 移动端视口 smoke | planned |
|
||||
| 移动端授权和开始必须由用户手势触发 | application/e2e-smoke | `src/games/bark-battle/application/BrowserMicrophoneInput.test.ts`, Playwright 移动端 smoke | planned |
|
||||
| 移动端结算面板不遮挡主要操作 | component/visual/smoke | `src/games/bark-battle/ui/BarkBattleResultPanel.test.tsx`, Playwright 移动端视口 smoke | planned |
|
||||
| 当前浏览器不支持 getUserMedia | component/application | `src/games/bark-battle/application/BrowserMicrophoneInput.test.ts`, `src/games/bark-battle/ui/BarkBattlePermissionPanel.test.tsx` | planned |
|
||||
| getUserMedia 调用失败但浏览器 API 存在 | component/application | `src/games/bark-battle/application/BrowserMicrophoneInput.test.ts`, `src/games/bark-battle/ui/BarkBattlePermissionPanel.test.tsx` | planned |
|
||||
| 非安全上下文导致麦克风不可用 | component/application | `src/games/bark-battle/application/BrowserMicrophoneInput.test.ts`, `src/games/bark-battle/ui/BarkBattlePermissionPanel.test.tsx` | planned |
|
||||
| 对战中离开页面停止采集 | application/integration | `src/games/bark-battle/application/BrowserMicrophoneInput.test.ts`, `src/games/bark-battle/application/BarkBattleController.test.ts` | planned |
|
||||
| 移动端授权和开始必须由用户手势触发 | infrastructure/application/e2e-smoke | `src/games/bark-battle/infrastructure/__tests__/BrowserMicrophoneInput.test.ts`, `src/games/bark-battle/application/__tests__/BarkBattleController.test.ts`, Playwright 移动端 smoke | planned |
|
||||
| 移动端结算面板不遮挡主要操作 | component/visual/smoke | `src/games/bark-battle/ui/__tests__/BarkBattleResultPanel.test.tsx`, Playwright 移动端视口 smoke | planned |
|
||||
| 当前浏览器不支持 getUserMedia | infrastructure/component | `src/games/bark-battle/infrastructure/__tests__/BrowserMicrophoneInput.test.ts`, `src/games/bark-battle/ui/__tests__/BarkBattlePermissionPanel.test.tsx` | planned |
|
||||
| getUserMedia 调用失败但浏览器 API 存在 | infrastructure/application/component | `src/games/bark-battle/infrastructure/__tests__/BrowserMicrophoneInput.test.ts`, `src/games/bark-battle/application/__tests__/BarkBattleController.test.ts`, `src/games/bark-battle/ui/__tests__/BarkBattlePermissionPanel.test.tsx` | planned |
|
||||
| 非安全上下文导致麦克风不可用 | infrastructure/application/component | `src/games/bark-battle/infrastructure/__tests__/BrowserMicrophoneInput.test.ts`, `src/games/bark-battle/application/__tests__/BarkBattleController.test.ts`, `src/games/bark-battle/ui/__tests__/BarkBattlePermissionPanel.test.tsx` | planned |
|
||||
| 对战中离开页面停止采集 | infrastructure/application/integration | `src/games/bark-battle/infrastructure/__tests__/BrowserMicrophoneInput.test.ts`, `src/games/bark-battle/application/__tests__/BarkBattleController.test.ts` | planned |
|
||||
| 刷新页面后不沿用旧局临时状态 | integration/smoke | Playwright 或人工 smoke 清单 | planned |
|
||||
|
||||
## 验收清单
|
||||
|
||||
- [ ] 权限允许、拒绝、API 不支持、麦克风不可读均有明确状态,且不会误进入 playing。
|
||||
- [ ] 权限允许、拒绝、非安全上下文、API 不支持、麦克风未找到/不可读、AudioContext 被拦截、校准超时或样本不可读均有明确状态,且不会误进入 playing。
|
||||
- [ ] 校准阶段会影响有效叫声阈值,低噪音不会增加叫声计数。
|
||||
- [ ] 有效叫声计数具备阈值、峰值间隔、持续时长约束。
|
||||
- [ ] 能量条根据双方推动力差值双向移动,并限制在 `-100` 到 `100`。
|
||||
|
||||
@@ -135,6 +135,7 @@ src/games/bark-battle/
|
||||
AudioAnalyserSampler.ts
|
||||
MicrophonePermission.ts
|
||||
__tests__/
|
||||
BrowserMicrophoneInput.test.ts
|
||||
AudioAnalyserSampler.test.ts
|
||||
|
||||
phaser/
|
||||
@@ -183,14 +184,34 @@ export type BarkBattlePhase =
|
||||
| 'countdown'
|
||||
| 'playing'
|
||||
| 'finished'
|
||||
| 'unsupported'
|
||||
| 'permission-denied'
|
||||
| 'unavailable'
|
||||
|
||||
export type BarkBattleSide = 'player' | 'opponent'
|
||||
|
||||
export type BarkBattleWinner = BarkBattleSide | 'draw' | null
|
||||
|
||||
export type BarkBattleDifficulty = 'easy' | 'normal' | 'hard'
|
||||
|
||||
export type BarkBattleUiState =
|
||||
| 'idle'
|
||||
| 'permission-ready'
|
||||
| 'microphone-authorized'
|
||||
| 'calibrating'
|
||||
| 'ready-countdown'
|
||||
| 'playing'
|
||||
| 'finished'
|
||||
| 'microphone-unavailable'
|
||||
|
||||
export type MicrophoneFailureReason =
|
||||
| 'unsupported'
|
||||
| 'permission-denied'
|
||||
| 'non-secure-context'
|
||||
| 'not-found'
|
||||
| 'not-readable'
|
||||
| 'audio-context-blocked'
|
||||
| 'calibration-timeout'
|
||||
| 'calibration-sample-unreadable'
|
||||
| 'unknown'
|
||||
```
|
||||
|
||||
关键数值:
|
||||
@@ -206,6 +227,9 @@ export type BarkBattleDifficulty = 'easy' | 'normal' | 'hard'
|
||||
```ts
|
||||
export type BarkBattleSnapshot = {
|
||||
phase: BarkBattlePhase
|
||||
uiState: BarkBattleUiState
|
||||
errorReason: MicrophoneFailureReason | null
|
||||
statusMessageKey: BarkBattleStatusMessageKey | null
|
||||
elapsedMs: number
|
||||
remainingMs: number
|
||||
countdownMs: number
|
||||
@@ -237,6 +261,17 @@ export type BarkBattleResult = {
|
||||
playerAveragePower: number
|
||||
score: number
|
||||
}
|
||||
|
||||
export type BarkBattleStatusMessageKey =
|
||||
| 'microphone-unsupported'
|
||||
| 'microphone-permission-denied'
|
||||
| 'microphone-non-secure-context'
|
||||
| 'microphone-not-found'
|
||||
| 'microphone-not-readable'
|
||||
| 'microphone-audio-context-blocked'
|
||||
| 'microphone-calibration-timeout'
|
||||
| 'microphone-calibration-sample-unreadable'
|
||||
| 'microphone-unknown-error'
|
||||
```
|
||||
|
||||
### 5.3 输入样本与叫声事件
|
||||
@@ -341,10 +376,11 @@ energy = clamp(energy + energyDelta, -100, 100)
|
||||
|
||||
```text
|
||||
permission → calibration → countdown → playing → finished
|
||||
↘ permission-denied
|
||||
↘ unsupported
|
||||
↘ unavailable
|
||||
```
|
||||
|
||||
`phase` 只表达 runtime 是否可继续参与局内流程;所有麦克风不可用、权限失败、非安全上下文和校准失败都统一收敛到 `phase: 'unavailable'`,再通过 `uiState: 'microphone-unavailable'` 与 `errorReason` 区分 HUD 展示和重试策略,避免把基础设施错误枚举直接扩散成 domain 阶段。
|
||||
|
||||
关键规则:
|
||||
|
||||
- `countdown` 结束才进入 `playing`。
|
||||
@@ -419,13 +455,29 @@ barkThreshold = clamp(ambientNoiseFloor + 0.12, 0.18, 0.55)
|
||||
export type MicrophoneFailureReason =
|
||||
| 'unsupported'
|
||||
| 'permission-denied'
|
||||
| 'non-secure-context'
|
||||
| 'not-found'
|
||||
| 'not-readable'
|
||||
| 'audio-context-blocked'
|
||||
| 'calibration-timeout'
|
||||
| 'calibration-sample-unreadable'
|
||||
| 'unknown'
|
||||
```
|
||||
|
||||
前端只根据错误分类展示可操作状态:重试授权、返回、或使用调试备用输入。不要把浏览器原始错误堆栈展示给玩家。
|
||||
错误来源与分层归属:
|
||||
|
||||
| 失败原因 | 主要检测位置 | controller snapshot 表达 | HUD 可区分状态 |
|
||||
| --- | --- | --- | --- |
|
||||
| 浏览器无 `mediaDevices.getUserMedia` | `BrowserMicrophoneInput.isSupported()` | `phase: 'unavailable'`, `uiState: 'microphone-unavailable'`, `errorReason: 'unsupported'` | 设备或浏览器不支持麦克风输入,只提供返回入口,不展示可开始声控按钮 |
|
||||
| 非安全上下文 | `BrowserMicrophoneInput.isSupported()` 或 `MicrophonePermission` 预检 `window.isSecureContext` | `phase: 'unavailable'`, `errorReason: 'non-secure-context'` | 当前环境无法使用麦克风,提示使用受支持的安全环境或返回 |
|
||||
| 用户拒绝授权 | `BrowserMicrophoneInput.requestPermission()` 捕获 `NotAllowedError` / `SecurityError` | `phase: 'unavailable'`, `errorReason: 'permission-denied'` | 提供重新授权或返回入口,不进入 calibration/countdown/playing |
|
||||
| 未检测到设备 | `getUserMedia` 捕获 `NotFoundError` / `DevicesNotFoundError` | `phase: 'unavailable'`, `errorReason: 'not-found'` | 展示麦克风不可用,可重试授权或返回 |
|
||||
| 设备被占用或不可读 | `getUserMedia` 捕获 `NotReadableError` / `TrackStartError` | `phase: 'unavailable'`, `errorReason: 'not-readable'` | 展示麦克风不可用,可重试授权或返回 |
|
||||
| AudioContext 被移动端策略拦截 | 用户手势后创建 / resume `AudioContext` 失败 | `phase: 'unavailable'`, `errorReason: 'audio-context-blocked'` | 提示点击重试,不自动循环请求 |
|
||||
| 校准超时 | `BarkBattleController` 在 calibration 阶段等待样本超出 `calibrationMaxWaitMs` | `phase: 'unavailable'`, `errorReason: 'calibration-timeout'` | 展示麦克风输入不可用,提供重试校准入口 |
|
||||
| 校准样本不可读 | `AudioAnalyserSampler.sample()` 持续返回空样本、NaN 或无法读取 buffer | `phase: 'unavailable'`, `errorReason: 'calibration-sample-unreadable'` | 展示麦克风输入不可用,提供重试校准入口 |
|
||||
|
||||
前端只根据错误分类展示可操作状态:重试授权、重试校准、返回、或使用调试备用输入。不要把浏览器原始错误堆栈展示给玩家。
|
||||
|
||||
## 8. Phaser Scene 切分
|
||||
|
||||
@@ -544,10 +596,13 @@ HUD 分区:
|
||||
|
||||
权限失败时:
|
||||
|
||||
- `unsupported`:展示“当前浏览器不支持麦克风输入”,提供返回入口。
|
||||
- `unsupported`:展示“当前浏览器不支持麦克风输入”,提供返回入口,不展示开始声控按钮。
|
||||
- `non-secure-context`:展示“当前环境无法使用麦克风”,提示切换到受支持的安全环境或返回。
|
||||
- `permission-denied`:展示简短说明和“重新授权”入口。
|
||||
- `not-found`:提示未检测到麦克风,提供返回入口。
|
||||
- `not-found`:提示未检测到麦克风,提供重试授权或返回入口。
|
||||
- `not-readable`:提示麦克风被占用或暂时不可读,提供重试授权或返回入口。
|
||||
- `audio-context-blocked`:提示点击重试。
|
||||
- `calibration-timeout` / `calibration-sample-unreadable`:提示麦克风输入不可用,提供“重新校准”和返回入口。
|
||||
|
||||
可选开发调试降级:
|
||||
|
||||
@@ -578,7 +633,9 @@ HUD 分区:
|
||||
建议测试:
|
||||
|
||||
- 权限允许后进入校准,再进入倒计时。
|
||||
- 权限拒绝后 phase 为 `permission-denied`,不进入 playing。
|
||||
- 权限拒绝后 `phase` 为 `unavailable`、`errorReason` 为 `permission-denied`,不进入 playing。
|
||||
- 非安全上下文、设备未找到、设备不可读、AudioContext 被拦截时,controller snapshot 都进入 `phase: 'unavailable'`,并保留可供 HUD 区分的 `errorReason`。
|
||||
- 校准超时或样本持续不可读时,controller snapshot 使用 `errorReason: 'calibration-timeout'` 或 `calibration-sample-unreadable`,并提供重试校准动作。
|
||||
- 提交 mock audio sample 后 snapshot 中玩家状态更新。
|
||||
- AI 对手 power 参与能量条拉锯。
|
||||
- `lastEvents` 只发布新增视觉事件。
|
||||
@@ -591,7 +648,9 @@ HUD 分区:
|
||||
|
||||
- playing 阶段展示倒计时和能量条。
|
||||
- energy 正负值映射到玩家 / 对手侧比例。
|
||||
- permission-denied 展示重试入口。
|
||||
- `errorReason: 'permission-denied'` 展示重试授权入口。
|
||||
- `errorReason: 'unsupported'` 展示返回入口且不展示开始声控按钮。
|
||||
- `not-found`、`not-readable`、`non-secure-context`、`audio-context-blocked`、`calibration-timeout`、`calibration-sample-unreadable` 分别映射到可区分的简短状态文案和对应操作。
|
||||
- finished 展示胜负、叫声次数和再来一局。
|
||||
- 移动端 class / 结构不依赖 Phaser Canvas 才能渲染。
|
||||
|
||||
@@ -609,7 +668,7 @@ HUD 分区:
|
||||
|
||||
```bash
|
||||
npm run check:encoding
|
||||
git diff -- docs/technical/BARK_BATTLE_2D_RUNTIME_TECHNICAL_PLAN_2026-05-11.md
|
||||
git diff -- docs/prd/BARK_BATTLE_BDD_2026-05-11.md docs/technical/BARK_BATTLE_2D_RUNTIME_TECHNICAL_PLAN_2026-05-11.md
|
||||
```
|
||||
|
||||
后续实现 domain 后建议:
|
||||
@@ -620,6 +679,14 @@ npm run typecheck
|
||||
npm run check:encoding
|
||||
```
|
||||
|
||||
后续实现 infrastructure/application 错误状态后建议:
|
||||
|
||||
```bash
|
||||
npm run test -- --run src/games/bark-battle/infrastructure/__tests__/BrowserMicrophoneInput.test.ts src/games/bark-battle/application/__tests__/BarkBattleController.test.ts
|
||||
npm run typecheck
|
||||
npm run check:encoding
|
||||
```
|
||||
|
||||
后续实现 HUD 后建议:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
[
|
||||
{
|
||||
"id": "bark-battle-player-back",
|
||||
"title": "玩家背对屏幕狗狗",
|
||||
"prompt": "竖屏手机游戏素材,背对屏幕的可爱小狗,站在下半屏中央,耳朵竖起,身体朝向远处对手,夸张卡通 2D 手游风,轮廓清晰,暖橙色毛发,适合做 sprite,透明背景或纯色背景,无文字、水印、UI、边框"
|
||||
},
|
||||
{
|
||||
"id": "bark-battle-opponent-front",
|
||||
"title": "对手面向屏幕狗狗",
|
||||
"prompt": "竖屏手机游戏素材,面向屏幕的可爱小狗,站在上半屏中央,张嘴准备汪汪叫,夸张卡通 2D 手游风,轮廓清晰,紫蓝色竞技光效,适合做 sprite,透明背景或纯色背景,无文字、水印、UI、边框"
|
||||
},
|
||||
{
|
||||
"id": "bark-battle-bark-particles",
|
||||
"title": "汪字粒子声浪",
|
||||
"prompt": "竖屏手机游戏特效素材,画面中心必须是完整清晰的中文汉字“汪”,包含左侧三点水偏旁“氵”和右侧“王”,字体由金黄色发光粒子组成,字形周围向外扩散圆形声浪冲击波与粉色火花,深色纯背景便于叠加,适合做游戏粒子特效贴图,无其他文字、水印、按钮、UI,不要只生成“王”字"
|
||||
}
|
||||
]
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.9 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 2.4 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 2.7 MiB |
@@ -0,0 +1,145 @@
|
||||
import { Buffer } from 'node:buffer';
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const repoRoot = process.cwd();
|
||||
const promptsPath = path.join(repoRoot, 'public', 'bark-battle-assets', 'bark-battle-image-prompts.json');
|
||||
const outDir = path.join(repoRoot, 'public', 'bark-battle-assets', 'generated');
|
||||
const args = new Set(process.argv.slice(2));
|
||||
|
||||
function readDotenv(fileName) {
|
||||
const filePath = path.join(repoRoot, fileName);
|
||||
if (!existsSync(filePath)) return {};
|
||||
const values = {};
|
||||
for (const line of readFileSync(filePath, 'utf8').split(/\r?\n/u)) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith('#')) continue;
|
||||
const match = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/u.exec(trimmed);
|
||||
if (!match) continue;
|
||||
let value = match[2].trim();
|
||||
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
values[match[1]] = value;
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
function resolveEnv() {
|
||||
const loaded = {
|
||||
...readDotenv('.env.example'),
|
||||
...readDotenv('.env.local'),
|
||||
...readDotenv('.env.secrets.local'),
|
||||
...process.env,
|
||||
};
|
||||
return {
|
||||
baseUrl: String(loaded.VECTOR_ENGINE_BASE_URL || '').trim().replace(/\/+$/u, ''),
|
||||
apiKey: String(loaded.VECTOR_ENGINE_API_KEY || '').trim(),
|
||||
timeoutMs: Number.parseInt(String(loaded.VECTOR_ENGINE_IMAGE_REQUEST_TIMEOUT_MS || 180000), 10),
|
||||
};
|
||||
}
|
||||
|
||||
function generationUrl(baseUrl) {
|
||||
return baseUrl.endsWith('/v1') ? `${baseUrl}/images/generations` : `${baseUrl}/v1/images/generations`;
|
||||
}
|
||||
|
||||
function collectStringsByKey(value, targetKey, output) {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((entry) => collectStringsByKey(entry, targetKey, output));
|
||||
return;
|
||||
}
|
||||
if (!value || typeof value !== 'object') return;
|
||||
for (const [key, nested] of Object.entries(value)) {
|
||||
if (key === targetKey) {
|
||||
if (typeof nested === 'string' && nested.trim()) output.push(nested.trim());
|
||||
if (Array.isArray(nested)) nested.forEach((entry) => typeof entry === 'string' && entry.trim() && output.push(entry.trim()));
|
||||
}
|
||||
collectStringsByKey(nested, targetKey, output);
|
||||
}
|
||||
}
|
||||
|
||||
function inferExtensionFromBytes(bytes) {
|
||||
if (bytes.subarray(0, 8).equals(Buffer.from('\x89PNG\r\n\x1A\n', 'binary'))) return 'png';
|
||||
if (bytes.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff]))) return 'jpg';
|
||||
if (bytes.subarray(0, 4).toString('ascii') === 'RIFF' && bytes.subarray(8, 12).toString('ascii') === 'WEBP') return 'webp';
|
||||
return 'png';
|
||||
}
|
||||
|
||||
async function fetchJson(url, options, timeoutMs) {
|
||||
const abortController = new AbortController();
|
||||
const timer = setTimeout(() => abortController.abort(), timeoutMs);
|
||||
try {
|
||||
const response = await fetch(url, { ...options, signal: abortController.signal });
|
||||
const text = await response.text();
|
||||
if (!response.ok) throw new Error(`VectorEngine ${response.status}: ${text.slice(0, 300)}`);
|
||||
return JSON.parse(text);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadUrl(url, timeoutMs) {
|
||||
const abortController = new AbortController();
|
||||
const timer = setTimeout(() => abortController.abort(), timeoutMs);
|
||||
try {
|
||||
const response = await fetch(url, { signal: abortController.signal });
|
||||
if (!response.ok) throw new Error(`download ${response.status}`);
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
const type = response.headers.get('content-type') || '';
|
||||
const extension = type.includes('webp') ? 'webp' : type.includes('jpeg') ? 'jpg' : 'png';
|
||||
return { bytes, extension };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
const rawTemplates = JSON.parse(readFileSync(promptsPath, 'utf8'));
|
||||
const onlyIds = process.argv
|
||||
.slice(2)
|
||||
.flatMap((arg, index, values) => (arg === '--only' ? String(values[index + 1] || '').split(',') : []))
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean);
|
||||
const templates = rawTemplates.filter((template) => !onlyIds.length || onlyIds.includes(template.id));
|
||||
const dryRun = args.has('--dry-run') || !args.has('--live');
|
||||
const requests = templates.map((template) => ({ id: template.id, title: template.title, body: { model: 'gpt-image-2-all', prompt: template.prompt, n: 1, size: '1024x1024' } }));
|
||||
if (dryRun) {
|
||||
console.log(JSON.stringify({ mode: 'dry-run', outDir, count: requests.length, requests }, null, 2));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const env = resolveEnv();
|
||||
if (!env.baseUrl || !env.apiKey) {
|
||||
console.error(JSON.stringify({ ok: false, error: 'Missing VECTOR_ENGINE_BASE_URL or VECTOR_ENGINE_API_KEY', hasBaseUrl: Boolean(env.baseUrl), hasApiKey: Boolean(env.apiKey) }));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
mkdirSync(outDir, { recursive: true });
|
||||
const files = [];
|
||||
for (const request of requests) {
|
||||
console.log(`Generating ${request.id}...`);
|
||||
const payload = await fetchJson(generationUrl(env.baseUrl), {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${env.apiKey}`, Accept: 'application/json', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request.body),
|
||||
}, env.timeoutMs);
|
||||
const urls = [];
|
||||
const b64 = [];
|
||||
collectStringsByKey(payload, 'url', urls);
|
||||
collectStringsByKey(payload, 'image', urls);
|
||||
collectStringsByKey(payload, 'image_url', urls);
|
||||
collectStringsByKey(payload, 'b64_json', b64);
|
||||
let image;
|
||||
const url = [...new Set(urls)].find((item) => /^https?:\/\//u.test(item));
|
||||
if (url) {
|
||||
image = await downloadUrl(url, env.timeoutMs);
|
||||
} else if (b64[0]) {
|
||||
const bytes = Buffer.from(b64[0], 'base64');
|
||||
image = { bytes, extension: inferExtensionFromBytes(bytes) };
|
||||
} else {
|
||||
throw new Error(`VectorEngine returned no image for ${request.id}`);
|
||||
}
|
||||
const outputPath = path.join(outDir, `${request.id}.${image.extension}`);
|
||||
writeFileSync(outputPath, image.bytes);
|
||||
files.push(outputPath);
|
||||
}
|
||||
console.log(JSON.stringify({ ok: true, count: files.length, files }, null, 2));
|
||||
@@ -1,4 +1,7 @@
|
||||
import crypto from 'node:crypto';
|
||||
import { createRequire } from 'node:module';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
|
||||
if (crypto.webcrypto) {
|
||||
if (typeof crypto.getRandomValues !== 'function') {
|
||||
@@ -13,4 +16,7 @@ if (crypto.webcrypto) {
|
||||
}
|
||||
}
|
||||
|
||||
await import('../node_modules/vite/bin/vite.js');
|
||||
const require = createRequire(import.meta.url);
|
||||
const vitePackageJsonPath = require.resolve('vite/package.json');
|
||||
const viteBinPath = join(dirname(vitePackageJsonPath), 'bin', 'vite.js');
|
||||
await import(pathToFileURL(viteBinPath).href);
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { BarkBattleRuntimeShell } from './games/bark-battle/ui/BarkBattleRuntimeShell';
|
||||
|
||||
export default function BarkBattlePlaygroundApp() {
|
||||
return <BarkBattleRuntimeShell />;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
export type BarkBattleConfig = {
|
||||
roundDurationMs: number;
|
||||
countdownMs: number;
|
||||
drawThreshold: number;
|
||||
barkThreshold: number;
|
||||
minBarkGapMs: number;
|
||||
minBarkDurationMs: number;
|
||||
maxBarkDurationMs: number;
|
||||
balanceFactor: number;
|
||||
calibrationMaxWaitMs: number;
|
||||
opponentBasePower: number;
|
||||
};
|
||||
|
||||
export const DEFAULT_BARK_BATTLE_CONFIG: BarkBattleConfig = {
|
||||
roundDurationMs: 30_000,
|
||||
countdownMs: 3_000,
|
||||
drawThreshold: 12,
|
||||
barkThreshold: 0.5,
|
||||
minBarkGapMs: 300,
|
||||
minBarkDurationMs: 90,
|
||||
maxBarkDurationMs: 900,
|
||||
balanceFactor: 32,
|
||||
calibrationMaxWaitMs: 4_000,
|
||||
opponentBasePower: 0.22,
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
import { type BarkBattleSession,createBarkBattleSession } from '../domain/BarkBattleSession';
|
||||
import type { MicrophoneFailureReason } from '../domain/BarkBattleTypes';
|
||||
import { BarkDetector } from '../domain/BarkDetector';
|
||||
import type { BarkBattleConfig } from './BarkBattleConfig';
|
||||
|
||||
export class BarkBattleController {
|
||||
private session: BarkBattleSession;
|
||||
private detector: BarkDetector;
|
||||
private sampleClockMs = 0;
|
||||
|
||||
constructor(private config: BarkBattleConfig) {
|
||||
this.session = createBarkBattleSession(config);
|
||||
this.detector = this.createDetector();
|
||||
}
|
||||
|
||||
getSnapshot() {
|
||||
return this.session.snapshot;
|
||||
}
|
||||
|
||||
updateConfig(config: BarkBattleConfig) {
|
||||
this.config = config;
|
||||
this.restart();
|
||||
}
|
||||
|
||||
finishNow() {
|
||||
if (this.session.snapshot.phase !== 'playing') {
|
||||
this.session = this.session.startMockRound();
|
||||
}
|
||||
if (this.session.snapshot.phase === 'countdown') {
|
||||
this.session = this.session.tick(this.session.snapshot.countdownMs);
|
||||
}
|
||||
this.session = this.session.tick(this.session.snapshot.remainingMs + 1);
|
||||
}
|
||||
|
||||
startWithMockInput() {
|
||||
this.session = createBarkBattleSession(this.config).startMockRound();
|
||||
this.detector = this.createDetector();
|
||||
this.sampleClockMs = 0;
|
||||
}
|
||||
|
||||
submitMockSample(volume: number) {
|
||||
const events = this.detector.acceptSample({ atMs: this.sampleClockMs, volume });
|
||||
for (const event of events) {
|
||||
this.session = this.session.applyPlayerBark(event);
|
||||
}
|
||||
}
|
||||
|
||||
tick(deltaMs: number) {
|
||||
this.sampleClockMs += deltaMs;
|
||||
this.session = this.session.tick(deltaMs);
|
||||
}
|
||||
|
||||
restart() {
|
||||
this.session = createBarkBattleSession(this.config);
|
||||
this.detector = this.createDetector();
|
||||
this.sampleClockMs = 0;
|
||||
}
|
||||
|
||||
failMicrophone(reason: MicrophoneFailureReason) {
|
||||
this.session = this.session.failMicrophone(reason);
|
||||
}
|
||||
|
||||
private createDetector() {
|
||||
return new BarkDetector({
|
||||
threshold: this.config.barkThreshold,
|
||||
minBarkGapMs: this.config.minBarkGapMs,
|
||||
minBarkDurationMs: this.config.minBarkDurationMs,
|
||||
maxBarkDurationMs: this.config.maxBarkDurationMs,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { DEFAULT_BARK_BATTLE_CONFIG } from '../BarkBattleConfig';
|
||||
import { BarkBattleController } from '../BarkBattleController';
|
||||
|
||||
describe('BarkBattleController', () => {
|
||||
it('mock 模式可跑通完整一局并生成结算', () => {
|
||||
const controller = new BarkBattleController({ ...DEFAULT_BARK_BATTLE_CONFIG, roundDurationMs: 1200, countdownMs: 300 });
|
||||
|
||||
controller.startWithMockInput();
|
||||
controller.tick(300);
|
||||
expect(controller.getSnapshot().phase).toBe('playing');
|
||||
|
||||
controller.submitMockSample(0.92);
|
||||
controller.tick(160);
|
||||
controller.submitMockSample(0.12);
|
||||
|
||||
expect(controller.getSnapshot().player.barkCount).toBe(1);
|
||||
expect(controller.getSnapshot().energy).toBeGreaterThan(0);
|
||||
|
||||
controller.tick(1200);
|
||||
expect(controller.getSnapshot().phase).toBe('finished');
|
||||
expect(controller.getSnapshot().result?.winner).toBe('player');
|
||||
});
|
||||
|
||||
it('麦克风失败时进入 unavailable 且不会进入 playing', () => {
|
||||
const controller = new BarkBattleController(DEFAULT_BARK_BATTLE_CONFIG);
|
||||
|
||||
controller.failMicrophone('permission-denied');
|
||||
controller.tick(5000);
|
||||
|
||||
expect(controller.getSnapshot()).toMatchObject({
|
||||
phase: 'unavailable',
|
||||
uiState: 'microphone-unavailable',
|
||||
errorReason: 'permission-denied',
|
||||
statusMessageKey: 'microphone-permission-denied',
|
||||
});
|
||||
});
|
||||
|
||||
it('restart 会重置上一局计数、能量和结果', () => {
|
||||
const controller = new BarkBattleController({ ...DEFAULT_BARK_BATTLE_CONFIG, roundDurationMs: 1, countdownMs: 0 });
|
||||
|
||||
controller.startWithMockInput();
|
||||
controller.tick(1);
|
||||
controller.submitMockSample(1);
|
||||
controller.tick(120);
|
||||
controller.submitMockSample(0.1);
|
||||
controller.tick(2);
|
||||
expect(controller.getSnapshot().result).not.toBeNull();
|
||||
|
||||
controller.restart();
|
||||
expect(controller.getSnapshot().phase).toBe('permission');
|
||||
expect(controller.getSnapshot().player.barkCount).toBe(0);
|
||||
expect(controller.getSnapshot().energy).toBe(0);
|
||||
expect(controller.getSnapshot().result).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { BarkBattleResult, BarkBattleWinner } from './BarkBattleTypes';
|
||||
|
||||
export function decideBarkBattleWinner(
|
||||
energy: number,
|
||||
drawThreshold: number,
|
||||
): BarkBattleWinner {
|
||||
if (energy > drawThreshold) {
|
||||
return 'player';
|
||||
}
|
||||
if (energy < -drawThreshold) {
|
||||
return 'opponent';
|
||||
}
|
||||
return 'draw';
|
||||
}
|
||||
|
||||
export function buildBarkBattleResult(input: {
|
||||
energy: number;
|
||||
drawThreshold: number;
|
||||
playerBarkCount: number;
|
||||
opponentBarkCount: number;
|
||||
}): BarkBattleResult {
|
||||
const winner = decideBarkBattleWinner(input.energy, input.drawThreshold);
|
||||
return {
|
||||
winner,
|
||||
playerBarkCount: input.playerBarkCount,
|
||||
opponentBarkCount: input.opponentBarkCount,
|
||||
finalEnergy: input.energy,
|
||||
score: Math.max(0, Math.round(input.energy + input.playerBarkCount * 120)),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import type { BarkBattleConfig } from '../application/BarkBattleConfig';
|
||||
import { buildBarkBattleResult } from './BarkBattleScoring';
|
||||
import type { BarkBattleEvent, BarkBattleSnapshot } from './BarkBattleTypes';
|
||||
import { advanceEnergy, clampEnergy } from './EnergyTugOfWar';
|
||||
import { computeOpponentPower } from './OpponentStrategy';
|
||||
|
||||
export class BarkBattleSession {
|
||||
constructor(
|
||||
private readonly config: BarkBattleConfig,
|
||||
readonly snapshot: BarkBattleSnapshot,
|
||||
) {}
|
||||
|
||||
startMockRound() {
|
||||
return new BarkBattleSession(this.config, {
|
||||
...this.snapshot,
|
||||
phase: this.config.countdownMs > 0 ? 'countdown' : 'playing',
|
||||
uiState: this.config.countdownMs > 0 ? 'ready-countdown' : 'playing',
|
||||
countdownMs: this.config.countdownMs,
|
||||
remainingMs: this.config.roundDurationMs,
|
||||
lastEvents: [],
|
||||
});
|
||||
}
|
||||
|
||||
tick(deltaMs: number) {
|
||||
if (this.snapshot.phase === 'finished' || this.snapshot.phase === 'unavailable') {
|
||||
return this.withEvents([]);
|
||||
}
|
||||
|
||||
if (this.snapshot.phase === 'countdown') {
|
||||
const countdownMs = Math.max(0, this.snapshot.countdownMs - deltaMs);
|
||||
return new BarkBattleSession(this.config, {
|
||||
...this.snapshot,
|
||||
phase: countdownMs <= 0 ? 'playing' : 'countdown',
|
||||
uiState: countdownMs <= 0 ? 'playing' : 'ready-countdown',
|
||||
countdownMs,
|
||||
remainingMs: this.config.roundDurationMs,
|
||||
lastEvents: [],
|
||||
});
|
||||
}
|
||||
|
||||
if (this.snapshot.phase !== 'playing') {
|
||||
return this.withEvents([]);
|
||||
}
|
||||
|
||||
const elapsedMs = this.snapshot.elapsedMs + deltaMs;
|
||||
const remainingMs = Math.max(0, this.snapshot.remainingMs - deltaMs);
|
||||
const opponentPower = computeOpponentPower(this.config, elapsedMs);
|
||||
const energy = advanceEnergy({
|
||||
energy: this.snapshot.energy,
|
||||
playerPower: this.snapshot.player.power,
|
||||
opponentPower,
|
||||
deltaMs,
|
||||
balanceFactor: this.config.balanceFactor,
|
||||
});
|
||||
const nextSnapshot: BarkBattleSnapshot = {
|
||||
...this.snapshot,
|
||||
elapsedMs,
|
||||
remainingMs,
|
||||
energy,
|
||||
opponent: {
|
||||
...this.snapshot.opponent,
|
||||
power: opponentPower,
|
||||
},
|
||||
player: {
|
||||
...this.snapshot.player,
|
||||
power: Math.max(0, this.snapshot.player.power * 0.78),
|
||||
},
|
||||
lastEvents: [],
|
||||
};
|
||||
|
||||
if (remainingMs > 0) {
|
||||
return new BarkBattleSession(this.config, nextSnapshot);
|
||||
}
|
||||
|
||||
const result = buildBarkBattleResult({
|
||||
energy,
|
||||
drawThreshold: this.config.drawThreshold,
|
||||
playerBarkCount: nextSnapshot.player.barkCount,
|
||||
opponentBarkCount: nextSnapshot.opponent.barkCount,
|
||||
});
|
||||
return new BarkBattleSession(this.config, {
|
||||
...nextSnapshot,
|
||||
phase: 'finished',
|
||||
uiState: 'finished',
|
||||
winner: result.winner,
|
||||
result,
|
||||
});
|
||||
}
|
||||
|
||||
applyPlayerBark(event: BarkBattleEvent) {
|
||||
if (this.snapshot.phase !== 'playing') {
|
||||
return this.withEvents([]);
|
||||
}
|
||||
|
||||
const playerPower = Math.min(1, Math.max(this.snapshot.player.power, event.peakVolume));
|
||||
return new BarkBattleSession(this.config, {
|
||||
...this.snapshot,
|
||||
energy: clampEnergy(this.snapshot.energy + event.peakVolume * 12),
|
||||
player: {
|
||||
barkCount: this.snapshot.player.barkCount + 1,
|
||||
power: playerPower,
|
||||
},
|
||||
lastEvents: [event],
|
||||
});
|
||||
}
|
||||
|
||||
failMicrophone(reason: BarkBattleSnapshot['errorReason']) {
|
||||
return new BarkBattleSession(this.config, {
|
||||
...this.snapshot,
|
||||
phase: 'unavailable',
|
||||
uiState: 'microphone-unavailable',
|
||||
errorReason: reason,
|
||||
statusMessageKey: reason ? MICROPHONE_STATUS_KEYS[reason] : null,
|
||||
lastEvents: [],
|
||||
});
|
||||
}
|
||||
|
||||
private withEvents(lastEvents: BarkBattleEvent[]) {
|
||||
return new BarkBattleSession(this.config, {
|
||||
...this.snapshot,
|
||||
lastEvents,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const MICROPHONE_STATUS_KEYS = {
|
||||
unsupported: 'microphone-unsupported',
|
||||
'permission-denied': 'microphone-permission-denied',
|
||||
'non-secure-context': 'microphone-non-secure-context',
|
||||
'not-found': 'microphone-not-found',
|
||||
'not-readable': 'microphone-not-readable',
|
||||
'audio-context-blocked': 'microphone-audio-context-blocked',
|
||||
'calibration-timeout': 'microphone-calibration-timeout',
|
||||
'calibration-sample-unreadable': 'microphone-calibration-sample-unreadable',
|
||||
unknown: 'microphone-unknown-error',
|
||||
} as const;
|
||||
|
||||
export function createBarkBattleSession(config: BarkBattleConfig) {
|
||||
return new BarkBattleSession(config, {
|
||||
phase: 'permission',
|
||||
uiState: 'permission-ready',
|
||||
errorReason: null,
|
||||
statusMessageKey: null,
|
||||
elapsedMs: 0,
|
||||
remainingMs: config.roundDurationMs,
|
||||
countdownMs: config.countdownMs,
|
||||
energy: 0,
|
||||
player: { barkCount: 0, power: 0 },
|
||||
opponent: { barkCount: 0, power: config.opponentBasePower },
|
||||
winner: null,
|
||||
result: null,
|
||||
lastEvents: [],
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
export type BarkBattlePhase =
|
||||
| 'permission'
|
||||
| 'calibration'
|
||||
| 'countdown'
|
||||
| 'playing'
|
||||
| 'finished'
|
||||
| 'unavailable';
|
||||
|
||||
export type BarkBattleSide = 'player' | 'opponent';
|
||||
export type BarkBattleWinner = BarkBattleSide | 'draw' | null;
|
||||
export type BarkBattleDifficulty = 'easy' | 'normal' | 'hard';
|
||||
|
||||
export type BarkBattleUiState =
|
||||
| 'idle'
|
||||
| 'permission-ready'
|
||||
| 'microphone-authorized'
|
||||
| 'calibrating'
|
||||
| 'ready-countdown'
|
||||
| 'playing'
|
||||
| 'finished'
|
||||
| 'microphone-unavailable';
|
||||
|
||||
export type MicrophoneFailureReason =
|
||||
| 'unsupported'
|
||||
| 'permission-denied'
|
||||
| 'non-secure-context'
|
||||
| 'not-found'
|
||||
| 'not-readable'
|
||||
| 'audio-context-blocked'
|
||||
| 'calibration-timeout'
|
||||
| 'calibration-sample-unreadable'
|
||||
| 'unknown';
|
||||
|
||||
export type BarkBattleStatusMessageKey =
|
||||
| 'microphone-unsupported'
|
||||
| 'microphone-permission-denied'
|
||||
| 'microphone-non-secure-context'
|
||||
| 'microphone-not-found'
|
||||
| 'microphone-not-readable'
|
||||
| 'microphone-audio-context-blocked'
|
||||
| 'microphone-calibration-timeout'
|
||||
| 'microphone-calibration-sample-unreadable'
|
||||
| 'microphone-unknown-error';
|
||||
|
||||
export type BarkAudioSample = {
|
||||
atMs: number;
|
||||
volume: number;
|
||||
};
|
||||
|
||||
export type BarkBattleEvent = {
|
||||
side: BarkBattleSide;
|
||||
atMs: number;
|
||||
peakVolume: number;
|
||||
durationMs: number;
|
||||
};
|
||||
|
||||
export type BarkBattleParticipantState = {
|
||||
barkCount: number;
|
||||
power: number;
|
||||
};
|
||||
|
||||
export type BarkBattleResult = {
|
||||
winner: BarkBattleWinner;
|
||||
playerBarkCount: number;
|
||||
opponentBarkCount: number;
|
||||
finalEnergy: number;
|
||||
score: number;
|
||||
};
|
||||
|
||||
export type BarkBattleSnapshot = {
|
||||
phase: BarkBattlePhase;
|
||||
uiState: BarkBattleUiState;
|
||||
errorReason: MicrophoneFailureReason | null;
|
||||
statusMessageKey: BarkBattleStatusMessageKey | null;
|
||||
elapsedMs: number;
|
||||
remainingMs: number;
|
||||
countdownMs: number;
|
||||
energy: number;
|
||||
player: BarkBattleParticipantState;
|
||||
opponent: BarkBattleParticipantState;
|
||||
winner: BarkBattleWinner;
|
||||
result: BarkBattleResult | null;
|
||||
lastEvents: BarkBattleEvent[];
|
||||
};
|
||||
@@ -0,0 +1,69 @@
|
||||
import type { BarkAudioSample, BarkBattleEvent } from './BarkBattleTypes';
|
||||
|
||||
export type BarkDetectorConfig = {
|
||||
threshold: number;
|
||||
minBarkGapMs: number;
|
||||
minBarkDurationMs: number;
|
||||
maxBarkDurationMs: number;
|
||||
};
|
||||
|
||||
type ActiveBark = {
|
||||
startMs: number;
|
||||
peakVolume: number;
|
||||
};
|
||||
|
||||
export class BarkDetector {
|
||||
private activeBark: ActiveBark | null = null;
|
||||
private lastAcceptedAtMs = Number.NEGATIVE_INFINITY;
|
||||
|
||||
constructor(private readonly config: BarkDetectorConfig) {}
|
||||
|
||||
acceptSample(sample: BarkAudioSample): BarkBattleEvent[] {
|
||||
const volume = clamp01(sample.volume);
|
||||
if (volume >= this.config.threshold) {
|
||||
this.activeBark = this.activeBark
|
||||
? {
|
||||
startMs: this.activeBark.startMs,
|
||||
peakVolume: Math.max(this.activeBark.peakVolume, volume),
|
||||
}
|
||||
: {
|
||||
startMs: sample.atMs,
|
||||
peakVolume: volume,
|
||||
};
|
||||
return [];
|
||||
}
|
||||
|
||||
if (!this.activeBark) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const activeBark = this.activeBark;
|
||||
this.activeBark = null;
|
||||
const durationMs = sample.atMs - activeBark.startMs;
|
||||
const accepted =
|
||||
durationMs >= this.config.minBarkDurationMs &&
|
||||
durationMs <= this.config.maxBarkDurationMs &&
|
||||
activeBark.startMs - this.lastAcceptedAtMs >= this.config.minBarkGapMs;
|
||||
|
||||
if (!accepted) {
|
||||
return [];
|
||||
}
|
||||
|
||||
this.lastAcceptedAtMs = activeBark.startMs;
|
||||
return [
|
||||
{
|
||||
side: 'player',
|
||||
atMs: activeBark.startMs,
|
||||
peakVolume: activeBark.peakVolume,
|
||||
durationMs,
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
function clamp01(value: number) {
|
||||
if (!Number.isFinite(value)) {
|
||||
return 0;
|
||||
}
|
||||
return Math.min(1, Math.max(0, value));
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
export type AdvanceEnergyInput = {
|
||||
energy: number;
|
||||
playerPower: number;
|
||||
opponentPower: number;
|
||||
deltaMs: number;
|
||||
balanceFactor: number;
|
||||
};
|
||||
|
||||
export function advanceEnergy(input: AdvanceEnergyInput) {
|
||||
const deltaSeconds = Math.max(0, input.deltaMs) / 1000;
|
||||
const powerDelta = input.playerPower - input.opponentPower;
|
||||
return clampEnergy(input.energy + powerDelta * input.balanceFactor * deltaSeconds);
|
||||
}
|
||||
|
||||
export function clampEnergy(value: number) {
|
||||
if (!Number.isFinite(value)) {
|
||||
return 0;
|
||||
}
|
||||
return Math.min(100, Math.max(-100, value));
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { BarkBattleConfig } from '../application/BarkBattleConfig';
|
||||
|
||||
export function computeOpponentPower(config: BarkBattleConfig, elapsedMs: number) {
|
||||
const pulse = 0.05 * Math.sin(elapsedMs / 480);
|
||||
return Math.min(1, Math.max(0, config.opponentBasePower + pulse));
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { DEFAULT_BARK_BATTLE_CONFIG } from '../../application/BarkBattleConfig';
|
||||
import { decideBarkBattleWinner } from '../BarkBattleScoring';
|
||||
import { createBarkBattleSession } from '../BarkBattleSession';
|
||||
|
||||
describe('BarkBattleSession', () => {
|
||||
it('能从校准完成进入倒计时、playing 并在归零后结算', () => {
|
||||
let session = createBarkBattleSession({ ...DEFAULT_BARK_BATTLE_CONFIG, roundDurationMs: 1000, countdownMs: 600 });
|
||||
|
||||
expect(session.snapshot.phase).toBe('permission');
|
||||
session = session.startMockRound();
|
||||
expect(session.snapshot.phase).toBe('countdown');
|
||||
|
||||
session = session.tick(600);
|
||||
expect(session.snapshot.phase).toBe('playing');
|
||||
expect(session.snapshot.remainingMs).toBe(1000);
|
||||
|
||||
session = session.tick(400);
|
||||
expect(session.snapshot.remainingMs).toBe(600);
|
||||
|
||||
session = session.applyPlayerBark({ atMs: 700, peakVolume: 0.9, durationMs: 140, side: 'player' });
|
||||
expect(session.snapshot.player.barkCount).toBe(1);
|
||||
expect(session.snapshot.energy).toBeGreaterThan(0);
|
||||
|
||||
session = session.tick(600);
|
||||
expect(session.snapshot.phase).toBe('finished');
|
||||
expect(session.snapshot.result?.winner).toBe('player');
|
||||
});
|
||||
|
||||
it('finished 后输入不再改变本局叫声计数和能量', () => {
|
||||
let session = createBarkBattleSession({ ...DEFAULT_BARK_BATTLE_CONFIG, roundDurationMs: 1, countdownMs: 0 }).startMockRound().tick(1);
|
||||
session = session.tick(1);
|
||||
const before = session.snapshot;
|
||||
|
||||
session = session.applyPlayerBark({ atMs: 200, peakVolume: 1, durationMs: 120, side: 'player' });
|
||||
|
||||
expect(session.snapshot.player.barkCount).toBe(before.player.barkCount);
|
||||
expect(session.snapshot.energy).toBe(before.energy);
|
||||
});
|
||||
});
|
||||
|
||||
describe('decideBarkBattleWinner', () => {
|
||||
it('按 drawThreshold 判定玩家胜、对手胜和平局', () => {
|
||||
expect(decideBarkBattleWinner(16, 12)).toBe('player');
|
||||
expect(decideBarkBattleWinner(-16, 12)).toBe('opponent');
|
||||
expect(decideBarkBattleWinner(8, 12)).toBe('draw');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { DEFAULT_BARK_BATTLE_CONFIG } from '../../application/BarkBattleConfig';
|
||||
import { BarkDetector } from '../BarkDetector';
|
||||
|
||||
describe('BarkDetector', () => {
|
||||
it('超过阈值且持续时长合规时只计为一次有效叫声', () => {
|
||||
const detector = new BarkDetector({
|
||||
threshold: 0.45,
|
||||
minBarkGapMs: DEFAULT_BARK_BATTLE_CONFIG.minBarkGapMs,
|
||||
minBarkDurationMs: 90,
|
||||
maxBarkDurationMs: 900,
|
||||
});
|
||||
|
||||
expect(detector.acceptSample({ atMs: 0, volume: 0.2 })).toEqual([]);
|
||||
expect(detector.acceptSample({ atMs: 40, volume: 0.72 })).toEqual([]);
|
||||
expect(detector.acceptSample({ atMs: 150, volume: 0.76 })).toEqual([]);
|
||||
const events = detector.acceptSample({ atMs: 180, volume: 0.2 });
|
||||
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]).toMatchObject({ side: 'player', peakVolume: 0.76 });
|
||||
expect(events[0]?.durationMs).toBe(140);
|
||||
});
|
||||
|
||||
it('持续噪音不会在每个 tick 无限计数', () => {
|
||||
const detector = new BarkDetector({
|
||||
threshold: 0.4,
|
||||
minBarkGapMs: 250,
|
||||
minBarkDurationMs: 80,
|
||||
maxBarkDurationMs: 600,
|
||||
});
|
||||
|
||||
const allEvents = [
|
||||
...detector.acceptSample({ atMs: 0, volume: 0.7 }),
|
||||
...detector.acceptSample({ atMs: 100, volume: 0.72 }),
|
||||
...detector.acceptSample({ atMs: 200, volume: 0.73 }),
|
||||
...detector.acceptSample({ atMs: 300, volume: 0.75 }),
|
||||
...detector.acceptSample({ atMs: 500, volume: 0.2 }),
|
||||
];
|
||||
|
||||
expect(allEvents).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('低于阈值的背景噪音、过短脉冲和冷却内峰值不计数', () => {
|
||||
const detector = new BarkDetector({
|
||||
threshold: 0.5,
|
||||
minBarkGapMs: 300,
|
||||
minBarkDurationMs: 80,
|
||||
maxBarkDurationMs: 800,
|
||||
});
|
||||
|
||||
expect(detector.acceptSample({ atMs: 0, volume: 0.48 })).toEqual([]);
|
||||
detector.acceptSample({ atMs: 20, volume: 0.9 });
|
||||
expect(detector.acceptSample({ atMs: 60, volume: 0.2 })).toEqual([]);
|
||||
|
||||
detector.acceptSample({ atMs: 500, volume: 0.88 });
|
||||
expect(detector.acceptSample({ atMs: 620, volume: 0.2 })).toHaveLength(1);
|
||||
|
||||
detector.acceptSample({ atMs: 700, volume: 0.9 });
|
||||
expect(detector.acceptSample({ atMs: 820, volume: 0.2 })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { advanceEnergy } from '../EnergyTugOfWar';
|
||||
|
||||
describe('advanceEnergy', () => {
|
||||
it('玩家推动力高于对手时能量增加', () => {
|
||||
expect(advanceEnergy({ energy: 0, playerPower: 0.8, opponentPower: 0.2, deltaMs: 1000, balanceFactor: 40 })).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('对手推动力高于玩家时能量减少', () => {
|
||||
expect(advanceEnergy({ energy: 0, playerPower: 0.1, opponentPower: 0.7, deltaMs: 1000, balanceFactor: 40 })).toBeLessThan(0);
|
||||
});
|
||||
|
||||
it('能量被限制在 -100 到 100 且双方相等时保持稳定', () => {
|
||||
expect(advanceEnergy({ energy: 98, playerPower: 1, opponentPower: 0, deltaMs: 2000, balanceFactor: 40 })).toBe(100);
|
||||
expect(advanceEnergy({ energy: -98, playerPower: 0, opponentPower: 1, deltaMs: 2000, balanceFactor: 40 })).toBe(-100);
|
||||
expect(advanceEnergy({ energy: 12, playerPower: 0.5, opponentPower: 0.5, deltaMs: 1000, balanceFactor: 40 })).toBeCloseTo(12);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { MicrophoneFailureReason } from '../domain/BarkBattleTypes';
|
||||
|
||||
export function mapGetUserMediaError(error: unknown): MicrophoneFailureReason {
|
||||
const name = error && typeof error === 'object' && 'name' in error ? String((error as { name?: unknown }).name) : '';
|
||||
if (name === 'NotAllowedError' || name === 'SecurityError') return 'permission-denied';
|
||||
if (name === 'NotFoundError' || name === 'DevicesNotFoundError') return 'not-found';
|
||||
if (name === 'NotReadableError' || name === 'TrackStartError') return 'not-readable';
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
export function isMicrophoneApiSupported(windowLike: { isSecureContext?: boolean; navigator?: Navigator | { mediaDevices?: { getUserMedia?: unknown } } }) {
|
||||
if (windowLike.isSecureContext === false) {
|
||||
return { ok: false as const, reason: 'non-secure-context' as const };
|
||||
}
|
||||
const getUserMedia = windowLike.navigator?.mediaDevices?.getUserMedia;
|
||||
if (typeof getUserMedia !== 'function') {
|
||||
return { ok: false as const, reason: 'unsupported' as const };
|
||||
}
|
||||
return { ok: true as const, reason: null };
|
||||
}
|
||||
|
||||
export function stopMediaStreamTracks(stream: MediaStream) {
|
||||
stream.getTracks().forEach((track) => track.stop());
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { isMicrophoneApiSupported, mapGetUserMediaError, stopMediaStreamTracks } from '../BrowserMicrophoneInput';
|
||||
|
||||
describe('BrowserMicrophoneInput', () => {
|
||||
it('区分非安全上下文和不支持 getUserMedia', () => {
|
||||
expect(isMicrophoneApiSupported({ isSecureContext: false })).toEqual({ ok: false, reason: 'non-secure-context' });
|
||||
expect(isMicrophoneApiSupported({ isSecureContext: true, navigator: {} })).toEqual({ ok: false, reason: 'unsupported' });
|
||||
});
|
||||
|
||||
it('映射常见 getUserMedia 错误', () => {
|
||||
expect(mapGetUserMediaError({ name: 'NotAllowedError' })).toBe('permission-denied');
|
||||
expect(mapGetUserMediaError({ name: 'NotFoundError' })).toBe('not-found');
|
||||
expect(mapGetUserMediaError({ name: 'NotReadableError' })).toBe('not-readable');
|
||||
expect(mapGetUserMediaError({ name: 'OtherError' })).toBe('unknown');
|
||||
});
|
||||
|
||||
it('停止 MediaStream 的所有音轨', () => {
|
||||
const stopA = vi.fn();
|
||||
const stopB = vi.fn();
|
||||
stopMediaStreamTracks({ getTracks: () => [{ stop: stopA }, { stop: stopB }] } as unknown as MediaStream);
|
||||
expect(stopA).toHaveBeenCalledTimes(1);
|
||||
expect(stopB).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,193 @@
|
||||
.bark-battle-hud {
|
||||
min-height: 100svh;
|
||||
color: #fff7ed;
|
||||
background: radial-gradient(circle at 50% 15%, rgba(251, 191, 36, 0.35), transparent 28%), linear-gradient(180deg, #1f1147 0%, #521b4f 48%, #130a28 100%);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
padding: max(18px, env(safe-area-inset-top)) 16px max(18px, env(safe-area-inset-bottom));
|
||||
box-sizing: border-box;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.bark-battle-hud__topline {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.bark-battle-hud__timer {
|
||||
justify-self: center;
|
||||
border-radius: 999px;
|
||||
padding: 8px 16px;
|
||||
background: rgba(15, 23, 42, 0.56);
|
||||
font-weight: 900;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.bark-battle-energy {
|
||||
position: relative;
|
||||
display: flex;
|
||||
height: 18px;
|
||||
border: 2px solid rgba(255, 247, 237, 0.78);
|
||||
border-radius: 999px;
|
||||
overflow: hidden;
|
||||
background: rgba(15, 23, 42, 0.48);
|
||||
}
|
||||
|
||||
.bark-battle-energy__side--player { background: linear-gradient(90deg, #f97316, #facc15); }
|
||||
.bark-battle-energy__side--opponent { background: linear-gradient(90deg, #60a5fa, #a78bfa); }
|
||||
|
||||
.bark-battle-arena {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
grid-template-rows: 1fr auto 1fr;
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
.bark-battle-dog {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.bark-battle-dog__body {
|
||||
font-size: clamp(92px, 30vw, 150px);
|
||||
filter: drop-shadow(0 18px 22px rgba(0, 0, 0, 0.42));
|
||||
}
|
||||
|
||||
.bark-battle-dog--player .bark-battle-dog__body {
|
||||
transform: rotateY(180deg) translateY(4px);
|
||||
}
|
||||
|
||||
.bark-battle-dog__label,
|
||||
.bark-battle-vs {
|
||||
font-weight: 900;
|
||||
text-shadow: 0 2px 10px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
|
||||
.bark-battle-vs {
|
||||
border-radius: 999px;
|
||||
padding: 10px 18px;
|
||||
background: rgba(255, 255, 255, 0.16);
|
||||
}
|
||||
|
||||
.bark-battle-controls,
|
||||
.bark-battle-result__stats {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
justify-content: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.bark-battle-controls button,
|
||||
.bark-battle-primary-button {
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
padding: 12px 18px;
|
||||
color: #1f1147;
|
||||
background: #fff7ed;
|
||||
font-weight: 900;
|
||||
}
|
||||
|
||||
.bark-battle-primary-button {
|
||||
background: linear-gradient(135deg, #facc15, #fb7185);
|
||||
}
|
||||
|
||||
.bark-battle-status-card,
|
||||
.bark-battle-result {
|
||||
margin: auto;
|
||||
width: min(92vw, 420px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.18);
|
||||
border-radius: 28px;
|
||||
padding: 24px;
|
||||
text-align: center;
|
||||
background: rgba(15, 23, 42, 0.68);
|
||||
box-shadow: 0 26px 60px rgba(0, 0, 0, 0.3);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
.bark-battle-result__stats span {
|
||||
min-width: 84px;
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.bark-battle-result__stats strong {
|
||||
font-size: 28px;
|
||||
}
|
||||
|
||||
.bark-battle-particles {
|
||||
position: absolute;
|
||||
inset: 18% 0 auto;
|
||||
pointer-events: none;
|
||||
text-align: center;
|
||||
font-size: clamp(30px, 10vw, 70px);
|
||||
font-weight: 950;
|
||||
letter-spacing: 0.08em;
|
||||
color: rgba(255, 247, 237, 0.88);
|
||||
text-shadow: 0 0 18px rgba(250, 204, 21, 0.75);
|
||||
animation: barkBattleParticlePop 820ms ease-out both;
|
||||
}
|
||||
|
||||
.bark-battle-debug-panel {
|
||||
position: fixed;
|
||||
right: 12px;
|
||||
bottom: max(12px, env(safe-area-inset-bottom));
|
||||
z-index: 8;
|
||||
width: min(92vw, 340px);
|
||||
max-height: 42svh;
|
||||
overflow: auto;
|
||||
border: 1px solid rgba(255, 255, 255, 0.18);
|
||||
border-radius: 22px;
|
||||
padding: 12px;
|
||||
color: #fff7ed;
|
||||
background: rgba(15, 23, 42, 0.72);
|
||||
box-shadow: 0 18px 46px rgba(0, 0, 0, 0.28);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
.bark-battle-debug-panel header,
|
||||
.bark-battle-debug-panel label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.bark-battle-debug-panel label {
|
||||
margin-top: 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.bark-battle-debug-panel input {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.bark-battle-debug-panel output {
|
||||
min-width: 44px;
|
||||
text-align: right;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.bark-battle-debug-panel__controls {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.bark-battle-debug-panel__controls button {
|
||||
flex: 1;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
padding: 8px 10px;
|
||||
color: #1f1147;
|
||||
background: #fff7ed;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
@keyframes barkBattleParticlePop {
|
||||
from { transform: translateY(28px) scale(0.7); opacity: 0; }
|
||||
42% { opacity: 1; }
|
||||
to { transform: translateY(-80px) scale(1.14); opacity: 0; }
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user