Files
cngo/public/js/client/main.js
T
rong cb28bbb49e feat: 围棋在线对战(Rust 服务端 + 零构建前端)
- 规则引擎:提子、禁自杀、全局同形(超级劫)、中国规则数子(白贴 7.5 目)、停一手终局
- 服务端:axum + tokio,房间/观战/包干计时/断线重连/语音中继,前端资源内嵌单文件
- 前端:Canvas 木纹棋盘(9/13/19 路、星位、四边坐标、翻转视角)、WebAudio 合成落子声、
  本机双人模式、终局数子面板
- 测试:16 组规则断言 + 5 组 e2e(提子/劫/数子/观战/语音/静态资源)
- 构建缓存遵循 dev-cache-layout:target/ 留项目内并忽略,前端零构建不产生包缓存
2026-10-23 10:12:55 +08:00

1155 lines
30 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
KOMI,
coordName,
decodeBoard,
isSuperko,
nearestPoint,
other,
play,
positionKey,
scoreArea,
} from '../shared/rules.js';
import { computeView, draw, toBoard } from './board.js';
import { sfx, unlockAudio } from './sound.js';
import { Recorder, blobToBase64, base64ToUrl, isSupported, MAX_SECONDS } from './voice.js';
/* ------------------------------- DOM 快捷方式 ------------------------------- */
const $ = (id) => {
const el = document.getElementById(id);
if (!el) throw new Error('missing element: ' + id);
return el;
};
const canvas = $('board');
const holder = $('holder');
const ctx = canvas.getContext('2d');
/* -------------------------------- 状态 -------------------------------- */
let mode = null; // 'online' | 'local' | null
let game = null;
let you = null;
let spec = false;
let code = null;
let hover = null;
let view = computeView(360, 19);
let totalMs = 0;
let spectatorCount = 0;
let clockBase = { b: 0, w: 0 };
let clockStamp = 0;
let clockRunning = false;
let selectedMinutes = 20;
let selectedSize = 19;
let localKeys = [];
/* -------------------------------- 语音互动 -------------------------------- */
let voiceList = [];
let voiceRoom = null;
const voiceCache = new Map();
let audioEl = null;
let playingId = null;
let pendingPlay = null;
let rec = null;
let recording = false;
let pressing = false;
let recStart = 0;
let recTimer = null;
let recLimit = null;
/* -------------------------------- 网络层 -------------------------------- */
let ws = null;
let conn = 'idle';
let wantRoom = null;
let reconnectTimer = null;
let reconnectAttempts = 0;
let queue = [];
function wsUrl() {
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
return `${proto}//${location.host}/ws`;
}
function setConn(next) {
conn = next;
const dot = $('status').querySelector('.dot');
dot.className = 'dot ' + next;
const label =
next === 'open'
? '已连接'
: next === 'connecting'
? '连接中…'
: next === 'closed'
? '断开'
: '未连接';
$('statusText').textContent = label;
}
function connect() {
if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) return;
setConn('connecting');
let sock;
try {
sock = new WebSocket(wsUrl());
} catch {
setConn('closed');
return;
}
ws = sock;
sock.onopen = () => {
setConn('open');
reconnectAttempts = 0;
const pending = queue.slice();
queue = [];
pending.forEach(send);
if (wantRoom) send(roomRequest());
};
sock.onmessage = (ev) => {
let msg;
try {
msg = JSON.parse(String(ev.data));
} catch {
return;
}
handleServer(msg);
};
sock.onclose = () => {
setConn('closed');
if (mode === 'online' && wantRoom) scheduleReconnect();
};
}
function roomRequest() {
if (!wantRoom) return { t: 'ping' };
if (wantRoom.code) return { t: 'join', code: wantRoom.code, spectate: wantRoom.spectate };
return {
t: 'create',
minutes: wantRoom.minutes ?? selectedMinutes,
size: wantRoom.size ?? selectedSize,
};
}
function scheduleReconnect() {
if (reconnectTimer !== null) return;
if (reconnectAttempts >= 12) {
toast('连接断开太久了,先回大厅吧');
return;
}
const delay = Math.min(5000, 700 * Math.pow(1.5, reconnectAttempts));
reconnectAttempts++;
reconnectTimer = window.setTimeout(() => {
reconnectTimer = null;
connect();
}, delay);
}
function send(msg) {
if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(msg));
else queue.push(msg);
}
function handleServer(msg) {
if (msg.t === 'error') {
toast(msg.msg);
return;
}
if (msg.t === 'left') {
toLobby();
return;
}
if (msg.t === 'clock') {
clockBase = { b: msg.clocks.b, w: msg.clocks.w };
clockStamp = performance.now();
updateClocks();
return;
}
if (msg.t === 'voice') {
onVoice(msg);
return;
}
if (msg.t === 'voiceData') {
onVoiceData(msg);
return;
}
applyState(msg);
}
/* ------------------------------ 状态 -> 界面 ------------------------------ */
function lastAt(history) {
for (let i = history.length - 1; i >= 0; i--) {
if (history[i].at != null) return history[i].at;
}
return null;
}
function applyState(m) {
const prevHistoryLen = game?.history.length ?? 0;
mode = 'online';
code = m.code;
you = m.you;
spec = m.spectating;
wantRoom = { code: m.code, spectate: m.spectating };
totalMs = m.totalMs;
spectatorCount = m.spectators;
if (voiceRoom !== m.code) {
clearVoiceCache();
voiceRoom = m.code;
}
voiceList = Array.isArray(m.voices) ? m.voices.slice() : [];
game = {
size: m.size,
board: decodeBoard(m.board, m.size),
turn: m.turn,
over: m.over,
winner: m.winner,
reason: m.reason,
history: m.history,
players: m.players,
rematch: m.rematch,
captures: m.captures ?? { b: 0, w: 0 },
score: m.score ?? null,
passes: m.passes ?? 0,
};
clockBase = { b: m.clocks.b, w: m.clocks.w };
clockStamp = performance.now();
clockRunning =
!m.over && m.totalMs > 0 && m.players.b.connected && m.players.w.connected;
hover = null;
if (m.history.length > prevHistoryLen) {
const last = m.history[m.history.length - 1];
if (m.over) {
sfx(you && m.winner !== you ? 'lose' : 'win');
} else if (last.cap > 0) sfx('capture');
else if (last.at == null) sfx('pass');
else sfx('move');
}
$('lobby').hidden = true;
if (location.hash.toUpperCase() !== '#' + m.code) {
try {
history.replaceState(null, '', '#' + m.code);
} catch {
/* ignore */
}
}
render();
}
function toLobby() {
mode = null;
game = null;
you = null;
spec = false;
code = null;
wantRoom = null;
hover = null;
clockRunning = false;
totalMs = 0;
spectatorCount = 0;
cancelRecording();
voiceList = [];
voiceRoom = null;
clearVoiceCache();
stopAudio();
if (location.hash) {
try {
history.replaceState(null, '', location.pathname);
} catch {
/* ignore */
}
}
$('lobby').hidden = false;
$('overlay').hidden = true;
$('roomline').hidden = true;
$('moves').innerHTML = '';
$('notice').hidden = true;
updateChips();
render();
}
function render() {
layout();
paint();
if (!game) {
$('roomline').hidden = true;
$('overlay').hidden = true;
renderVoice();
return;
}
$('roomline').hidden = false;
$('roomTag').textContent = code ? `房号 ${code}` : '本机双人';
$('copyBtn').hidden = !code;
const opp = you ? other(you) : null;
paintPlayer('pBlack', 'b', you === 'b', opp === 'b');
paintPlayer('pWhite', 'w', you === 'w', opp === 'w');
$('capBlack').textContent = `提 ${game.captures.b ?? 0}`;
$('capWhite').textContent = `提 ${game.captures.w ?? 0}`;
const bar = $('turnbar');
const who = game.turn === 'b' ? '黑方' : '白方';
if (game.over) {
bar.className = 'turnbar done';
bar.textContent = resultTitle();
} else if (spec) {
bar.className = 'turnbar';
bar.textContent = `观战中 · ${who}思考中`;
} else if (mode === 'online' && you && game.turn === you) {
bar.className = 'turnbar mine';
bar.textContent = `轮到你落子(${you === 'b' ? '黑' : '白'})`;
} else if (mode === 'local') {
bar.className = 'turnbar mine';
bar.textContent = `${who}落子(本机双人)`;
} else {
bar.className = 'turnbar';
bar.textContent = `${who}思考中…`;
}
const notice = $('notice');
if (!game.over && game.passes === 1) {
notice.hidden = false;
notice.textContent = '对方停了一手 —— 你再停一手,双方就终局数子';
} else {
notice.hidden = true;
}
paintMoves();
updateClocks();
renderVoice();
const badge = $('specBadge');
badge.hidden = !spec && spectatorCount === 0;
badge.textContent = spec
? `观战中 · ${spectatorCount} 人在看`
: `${spectatorCount} 人观战`;
$('resignBtn').disabled = game.over || spec;
$('passBtn').disabled = game.over || spec || !myTurn();
const opponentMissing =
mode === 'online' && !spec && you !== null && game.players[other(you)].connected === false;
if (game.over) showResultOverlay();
else if (opponentMissing) showWaitOverlay();
else $('overlay').hidden = true;
}
function paintPlayer(id, color, isYou, isOpp) {
const card = $(id);
const g = game;
const connected = g.players[color].connected;
const turnNow = !g.over && g.turn === color;
card.classList.toggle('active', turnNow);
card.classList.toggle('you', isYou);
const tag = isYou ? '你' : isOpp ? '对手' : '';
card.querySelector('.pname').textContent =
(color === 'b' ? '黑方' : '白方') + (tag ? ` · ${tag}` : '');
const st = card.querySelector('.pstate');
st.textContent = g.over
? g.winner === color
? '胜'
: g.winner
? '负'
: '和'
: mode === 'local'
? turnNow
? '该落子'
: '等待'
: connected
? turnNow
? '该落子'
: '在线'
: '离线';
card.classList.toggle('offline', mode === 'online' && !connected);
}
function paintMoves() {
const box = $('moves');
const h = game?.history ?? [];
if (!h.length) {
box.innerHTML = '<div class="empty">还没有落子记录</div>';
return;
}
const rows = [];
for (let i = 0; i < h.length; i += 2) {
const a = h[i];
const b = h[i + 1];
const cell = (mv) => {
if (!mv) return '';
const cap = mv.cap ? `<em>提${mv.cap}</em>` : '';
return `${mv.note}${cap}`;
};
rows.push(
`<div class="mvrow"><span class="no">${i / 2 + 1}</span>` +
`<span class="mvb${a?.color === 'b' ? ' hl' : ''}">${cell(a)}</span>` +
`<span class="mvw${b?.color === 'w' ? ' hl' : ''}">${cell(b)}</span></div>`,
);
}
box.innerHTML = rows.join('');
box.scrollTop = box.scrollHeight;
}
/* -------------------------------- 计时 -------------------------------- */
function displayClocks() {
const out = { b: clockBase.b, w: clockBase.w };
if (clockRunning && game) {
const el = performance.now() - clockStamp;
out[game.turn] = Math.max(0, out[game.turn] - el);
}
return out;
}
function fmtClock(ms) {
if (totalMs <= 0) return '—';
const t = Math.max(0, Math.ceil(ms / 1000));
const h = Math.floor(t / 3600);
const m = Math.floor((t % 3600) / 60);
const s = t % 60;
if (h > 0) return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
return `${m}:${String(s).padStart(2, '0')}`;
}
function updateClocks() {
const d = displayClocks();
const black = $('timeBlack');
const white = $('timeWhite');
black.textContent = fmtClock(d.b);
white.textContent = fmtClock(d.w);
const low = (ms) => totalMs > 0 && clockRunning && ms <= 60000;
black.classList.toggle('low', low(d.b));
white.classList.toggle('low', low(d.w));
}
function tick() {
if (!game) return;
if (mode === 'local' && clockRunning && !game.over && totalMs > 0) {
const d = displayClocks();
if (d[game.turn] <= 0) {
clockRunning = false;
game.over = true;
game.winner = other(game.turn);
game.reason = 'timeout';
sfx('lose');
render();
return;
}
}
updateClocks();
}
/* ------------------------------- 结果展示 ------------------------------- */
const REASON_TEXT = {
scored: '双方停手,数子终局',
resign: '认输',
timeout: '超时',
};
function sideName(c) {
return c === 'b' ? '黑方' : c === 'w' ? '白方' : '';
}
function resultTitle() {
const g = game;
if (!g.winner) return '和棋';
if (mode === 'local' || !you) return `${sideName(g.winner)}胜`;
return g.winner === you ? '你赢了' : '你输了';
}
function showResultOverlay() {
const g = game;
$('ovWait').hidden = true;
$('ovResult').hidden = false;
$('overlay').hidden = false;
const reason = g.reason ? REASON_TEXT[g.reason] ?? g.reason : '';
$('ovTitle').textContent = resultTitle();
$('ovTitle').className = g.winner === 'b' ? 'win-b' : g.winner === 'w' ? 'win-w' : 'win-draw';
const bits = [];
if (g.winner) bits.push(`${sideName(g.winner)}获胜`);
if (reason) bits.push(reason);
if (g.captures) {
const total = (g.captures.b ?? 0) + (g.captures.w ?? 0);
if (total > 0) bits.push(`共提 ${total} 子`);
}
$('ovText').textContent = bits.join(' · ');
const line = $('ovScore');
if (g.score) {
const s = g.score;
line.hidden = false;
line.innerHTML =
`<span class="sc black">黑 ${fmtScore(s.black)}</span>` +
`<span class="sc vs">:</span>` +
`<span class="sc white">白 ${fmtScore(s.white)}</span>` +
`<span class="sc note">贴 ${s.komi} 目 · ${sideName(s.winner ?? g.winner)}胜 ${fmtScore(s.margin)} 目</span>`;
} else {
line.hidden = true;
}
const btn = $('ovRematch');
if (spec) {
btn.hidden = true;
$('ovLobby').textContent = '退出观战';
return;
}
btn.hidden = false;
$('ovLobby').textContent = '返回大厅';
const voted = you ? g.rematch.indexOf(you) >= 0 : false;
btn.disabled = voted;
btn.textContent = voted ? '等待对手确认…' : '再来一局';
}
function fmtScore(v) {
const n = Number(v) || 0;
return Number.isInteger(n) ? String(n) : n.toFixed(1);
}
function showWaitOverlay() {
$('ovResult').hidden = true;
$('ovWait').hidden = false;
$('overlay').hidden = false;
$('ovCode').textContent = code ?? '----';
}
function toast(text) {
const el = $('toast');
el.textContent = text;
el.classList.add('show');
window.clearTimeout(toast._t);
toast._t = window.setTimeout(() => el.classList.remove('show'), 2400);
}
/* -------------------------------- 画布 -------------------------------- */
function layout() {
const w = holder.clientWidth || 320;
const size = game?.size ?? selectedSize;
const flipped = mode === 'online' && you === 'w';
view = computeView(w, size);
view.flipped = flipped;
const dpr = Math.min(window.devicePixelRatio || 1, 3);
canvas.width = Math.round(view.width * dpr);
canvas.height = Math.round(view.height * dpr);
canvas.style.width = view.width + 'px';
canvas.style.height = view.height + 'px';
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
function paint() {
const size = game?.size ?? selectedSize;
const board = game?.board ?? new Uint8Array(size * size);
draw(ctx, view, {
board,
last: game ? lastAt(game.history) : null,
hover,
ghost: myTurn() ? game.turn : null,
});
}
/* ------------------------------ 交互逻辑 ------------------------------ */
function myTurn() {
if (!game || game.over || spec) return false;
if (mode === 'local') return true;
return you !== null && game.turn === you;
}
function attempt(at) {
if (!game || game.over) return;
if (!myTurn()) {
if (spec) toast('你在观战,不能落子');
else if (mode === 'online') toast('等一下,还没轮到你');
return;
}
// 本地先挡一次明显不合法(服务端还会再判一次)
if (game.board[at] !== 0) {
toast('这里已经有子了');
return;
}
if (mode === 'online') {
send({ t: 'move', at });
hover = null;
paint();
} else {
doLocalMove(at);
}
}
function doPass() {
if (!game || game.over) return;
if (!myTurn()) {
toast('还没轮到你');
return;
}
if (mode === 'online') {
send({ t: 'pass' });
return;
}
// 本地双人
const g = game;
g.passes = (g.passes ?? 0) + 1;
g.history.push({ at: null, note: '停一手', color: g.turn, cap: 0 });
localKeys.push(positionKey(g.board, other(g.turn)));
g.turn = other(g.turn);
sfx('pass');
if (g.passes >= 2) {
const s = scoreArea(g.board, g.size, KOMI);
g.over = true;
g.score = s;
g.winner = s.winner;
g.reason = 'scored';
clockRunning = false;
sfx('win');
}
render();
}
function doLocalMove(at) {
const g = game;
const res = play(g.board, g.size, at, g.turn);
if (!res) {
toast('这里不能下(有子或者是禁着点)');
return;
}
const key = positionKey(res.board, other(g.turn));
if (isSuperko(localKeys, key)) {
toast('打劫:不能立刻下回同一个局面,先到别处应一手');
return;
}
if (totalMs > 0 && clockRunning) {
clockBase = displayClocks();
clockStamp = performance.now();
}
g.board = res.board;
g.captures[g.turn] = (g.captures[g.turn] ?? 0) + res.captured.length;
g.history.push({
at,
note: coordName(g.size, at),
color: g.turn,
cap: res.captured.length,
});
g.passes = 0;
localKeys.push(key);
g.turn = other(g.turn);
hover = null;
if (res.captured.length) sfx('capture');
else sfx('move');
render();
}
function pointAt(ev) {
const rect = canvas.getBoundingClientRect();
const px = ((ev.clientX - rect.left) / rect.width) * view.width;
const py = ((ev.clientY - rect.top) / rect.height) * view.height;
const [bx, by] = toBoard(view, px, py);
return nearestPoint(view.size, bx, by, 0.55);
}
function onPointerDown(ev) {
ev.preventDefault();
unlockAudio();
if (!game || game.over) return;
const at = pointAt(ev);
if (at == null) return;
attempt(at);
}
function onPointerMove(ev) {
if (ev.pointerType !== 'mouse' || !game || game.over || !myTurn()) {
if (hover !== null) {
hover = null;
paint();
}
return;
}
const at = pointAt(ev);
const next = at != null && game.board[at] === 0 ? at : null;
if (next !== hover) {
hover = next;
paint();
}
}
function onPointerLeave() {
if (hover !== null) {
hover = null;
paint();
}
}
/* ------------------------------- 本地双人 ------------------------------- */
function startLocal() {
unlockAudio();
mode = 'local';
you = null;
spec = false;
code = null;
wantRoom = null;
hover = null;
totalMs = selectedMinutes > 0 ? selectedMinutes * 60 * 1000 : 0;
clockBase = { b: totalMs, w: totalMs };
clockStamp = performance.now();
clockRunning = totalMs > 0;
spectatorCount = 0;
const size = selectedSize;
const board = new Uint8Array(size * size);
localKeys = [positionKey(board, 'b')];
game = {
size,
board,
turn: 'b',
over: false,
history: [],
players: {
b: { connected: true, name: '黑方' },
w: { connected: true, name: '白方' },
},
rematch: [],
captures: { b: 0, w: 0 },
passes: 0,
score: null,
};
$('lobby').hidden = true;
$('overlay').hidden = true;
render();
}
/* -------------------------------- 大厅 -------------------------------- */
function createRoom() {
unlockAudio();
mode = 'online';
requestRoom({ minutes: selectedMinutes, size: selectedSize, spectate: false });
}
function joinRoom(raw, spectate = false) {
const c = raw.replace(/[^0-9a-zA-Z]/g, '').toUpperCase();
if (c.length < 4) {
toast('房号是 4 位,检查一下');
return;
}
unlockAudio();
mode = 'online';
requestRoom({ code: c, spectate });
}
/** 统一入口:记住想去哪个房间,连上就自动发请求(断线重连也走这条路) */
function requestRoom(req) {
wantRoom = req;
if (conn === 'open') send(roomRequest());
else connect();
}
function updateChips() {
document.querySelectorAll('#tcRow .chip').forEach((el) => {
el.classList.toggle('on', Number(el.dataset.min) === selectedMinutes);
});
document.querySelectorAll('#sizeRow .chip').forEach((el) => {
el.classList.toggle('on', Number(el.dataset.size) === selectedSize);
});
}
function inviteLink() {
return `${location.origin}${location.pathname}#${code ?? ''}`;
}
async function copyInvite() {
const text = inviteLink();
try {
await navigator.clipboard.writeText(text);
toast('邀请链接已复制');
} catch {
const ta = document.createElement('textarea');
ta.value = text;
document.body.appendChild(ta);
ta.select();
try {
document.execCommand('copy');
toast('邀请链接已复制');
} catch {
toast(text);
}
ta.remove();
}
}
/* -------------------------------- 绑定 -------------------------------- */
function bind() {
canvas.addEventListener('pointerdown', onPointerDown);
canvas.addEventListener('pointermove', onPointerMove);
canvas.addEventListener('pointerleave', onPointerLeave);
$('createBtn').addEventListener('click', createRoom);
$('joinBtn').addEventListener('click', () => joinRoom($('codeInput').value));
$('watchBtn').addEventListener('click', () => joinRoom($('codeInput').value, true));
$('codeInput').addEventListener('keydown', (e) => {
if (e.key === 'Enter') joinRoom($('codeInput').value);
});
$('codeInput').addEventListener('input', (e) => {
const el = e.target;
el.value = el.value.toUpperCase().replace(/[^0-9A-Z]/g, '').slice(0, 4);
});
$('localBtn').addEventListener('click', startLocal);
$('tcRow').addEventListener('click', (e) => {
const el = e.target.closest('.chip');
if (!el) return;
selectedMinutes = Number(el.dataset.min) || 0;
updateChips();
});
$('sizeRow').addEventListener('click', (e) => {
const el = e.target.closest('.chip');
if (!el) return;
selectedSize = Number(el.dataset.size) || 19;
updateChips();
render();
});
$('copyBtn').addEventListener('click', copyInvite);
$('ovCopy').addEventListener('click', copyInvite);
const leave = () => {
send({ t: 'leave' });
toLobby();
};
$('lobbyBtn').addEventListener('click', leave);
$('ovLobby').addEventListener('click', leave);
$('ovLobby2').addEventListener('click', leave);
$('passBtn').addEventListener('click', doPass);
$('resignBtn').addEventListener('click', () => {
if (!game || game.over) return;
if (mode === 'local') {
if (!confirm('认输?')) return;
game.over = true;
game.winner = other(game.turn);
game.reason = 'resign';
clockRunning = false;
sfx('lose');
render();
return;
}
if (!confirm('确定认输?')) return;
send({ t: 'resign' });
});
$('ovRematch').addEventListener('click', () => {
if (!game) return;
if (mode === 'local') {
startLocal();
return;
}
send({ t: 'rematch' });
});
window.addEventListener('resize', render);
window.addEventListener('orientationchange', () => window.setTimeout(render, 120));
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible' && mode === 'online' && wantRoom && conn !== 'open') {
connect();
}
});
window.addEventListener('hashchange', () => {
const c = location.hash.replace('#', '').toUpperCase();
if (c && c !== code) joinRoom(c);
});
window.addEventListener('keydown', (e) => {
if (e.key === 'p' || e.key === 'P') {
if (game && !game.over && myTurn() && document.activeElement !== $('codeInput')) doPass();
}
});
window.setInterval(tick, 250);
bindVoice();
}
/* -------------------------------- 启动 -------------------------------- */
function boot() {
bind();
setConn('idle');
$('codeInput').setAttribute('autocomplete', 'off');
$('codeInput').setAttribute('inputmode', 'latin');
updateChips();
const fromHash = location.hash.replace('#', '').toUpperCase();
if (/^[0-9A-Z]{4}$/.test(fromHash)) {
$('codeInput').value = fromHash;
joinRoom(fromHash);
} else {
render();
}
}
boot();
/* -------------------------------- 语音互动 -------------------------------- */
function clearVoiceCache() {
for (const url of voiceCache.values()) {
try {
URL.revokeObjectURL(url);
} catch {
/* ignore */
}
}
voiceCache.clear();
}
function stopAudio() {
if (audioEl) {
try {
audioEl.pause();
} catch {
/* ignore */
}
audioEl = null;
}
playingId = null;
}
function upsertVoice(meta) {
if (!meta || !meta.id) return;
const i = voiceList.findIndex((v) => v.id === meta.id);
if (i >= 0) voiceList[i] = meta;
else voiceList.push(meta);
voiceList.sort((a, b) => a.id - b.id);
}
function voiceTime(at) {
try {
return new Date(at).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
} catch {
return '';
}
}
function voiceSecs(ms) {
const s = Math.max(0.1, (ms || 0) / 1000);
return s < 10 ? s.toFixed(1) : String(Math.round(s));
}
function renderVoice() {
const btn = document.getElementById('pttBtn');
const list = document.getElementById('voiceList');
if (!btn || !list) return;
const canTalk = mode === 'online' && !!you && !spec;
const label = btn.querySelector('.ptt-label');
btn.classList.toggle('rec', recording);
btn.disabled = !canTalk && !recording;
if (label) {
label.textContent = recording
? `松手发送 · ${((performance.now() - recStart) / 1000).toFixed(1)}s`
: '按住说话';
}
const hint = $('voiceHint');
if (recording) hint.textContent = `录音中 · 最长 ${MAX_SECONDS} 秒`;
else if (mode !== 'online') hint.textContent = '联机对局里才能用';
else if (spec) hint.textContent = '观战中只能听';
else if (canTalk) hint.textContent = '按住说话,松手自动发';
else hint.textContent = '还没连上服务端';
if (!voiceList.length) {
list.innerHTML = '<div class="empty">还没有语音留言</div>';
return;
}
const fromBottom = list.scrollHeight - list.scrollTop - list.clientHeight < 24;
list.innerHTML = voiceList
.map((v) => {
const mine = !!you && v.from === you;
const playing = v.id === playingId;
return (
`<button type="button" class="vitem${mine ? ' mine' : ''}${playing ? ' playing' : ''}" data-id="${v.id}">` +
`<span class="vico">${playing ? '❚❚' : '▶'}</span>` +
`<span class="vwho">${v.from === 'b' ? '黑方' : '白方'}${mine ? ' · 我' : ''}</span>` +
`<span class="vdur">${voiceSecs(v.durationMs)}s</span>` +
`<span class="vtime">${voiceTime(v.at)}</span>` +
`</button>`
);
})
.join('');
if (fromBottom) list.scrollTop = list.scrollHeight;
}
function playUrl(url, id) {
stopAudio();
const a = new Audio(url);
a.preload = 'auto';
audioEl = a;
playingId = id;
renderVoice();
a.onended = () => {
if (playingId === id) {
playingId = null;
audioEl = null;
renderVoice();
}
};
const p = a.play();
if (p && typeof p.catch === 'function') {
p.catch(() => {
if (playingId === id) {
playingId = null;
audioEl = null;
renderVoice();
}
toast('浏览器拦了自动播放,点一下那条记录');
});
}
}
function playVoice(id) {
const url = voiceCache.get(id);
if (url) {
playUrl(url, id);
return;
}
pendingPlay = id;
send({ t: 'voiceGet', id });
}
function onVoice(msg) {
let url = voiceCache.get(msg.id);
if (!url) {
url = base64ToUrl(msg.data, msg.mime);
voiceCache.set(msg.id, url);
}
upsertVoice({ id: msg.id, from: msg.from, at: msg.at, durationMs: msg.durationMs });
if (msg.from !== you) playUrl(url, msg.id);
else renderVoice();
}
function onVoiceData(msg) {
if (!voiceCache.has(msg.id)) voiceCache.set(msg.id, base64ToUrl(msg.data, msg.mime));
const url = voiceCache.get(msg.id);
if (pendingPlay === msg.id) {
pendingPlay = null;
playUrl(url, msg.id);
}
}
async function startRecording() {
if (recording) return;
if (mode !== 'online') {
toast('语音只在联机对局里可用');
return;
}
if (!you) {
toast('观战中只能听,不能发');
return;
}
if (conn !== 'open') {
toast('还没连上服务端,稍等一下');
return;
}
if (!isSupported()) {
toast('这个浏览器不支持录音');
return;
}
unlockAudio();
const r = new Recorder();
rec = r;
try {
await r.start();
} catch (e) {
if (rec === r) rec = null;
const name = e && e.name;
toast(
name === 'NotAllowedError'
? '麦克风没给权限'
: name === 'NotFoundError'
? '没找到麦克风'
: '麦克风打不开',
);
return;
}
if (rec !== r || !pressing) {
r.cancel();
if (rec === r) rec = null;
return;
}
recording = true;
recStart = performance.now();
renderVoice();
recTimer = window.setInterval(renderVoice, 100);
recLimit = window.setTimeout(() => {
stopRecording();
}, MAX_SECONDS * 1000);
}
async function stopRecording() {
if (!recording || !rec) return;
window.clearInterval(recTimer);
recTimer = null;
window.clearTimeout(recLimit);
recLimit = null;
const r = rec;
rec = null;
recording = false;
const result = await r.stop();
renderVoice();
if (!result) return;
if (result.durationMs < 300) {
toast('说得太快了,按住多说一会儿');
return;
}
let b64 = '';
try {
b64 = await blobToBase64(result.blob);
} catch {
toast('录音处理失败');
return;
}
if (!b64) return;
if (b64.length > 640 * 1024) {
toast('这段太长,说短一点');
return;
}
send({ t: 'voice', mime: result.mime, durationMs: result.durationMs, data: b64 });
}
function cancelRecording() {
window.clearInterval(recTimer);
recTimer = null;
window.clearTimeout(recLimit);
recLimit = null;
const r = rec;
rec = null;
recording = false;
if (r) r.cancel();
renderVoice();
}
function bindVoice() {
const btn = $('pttBtn');
const list = $('voiceList');
btn.addEventListener('pointerdown', (e) => {
e.preventDefault();
if (btn.disabled || recording) return;
pressing = true;
try {
btn.setPointerCapture(e.pointerId);
} catch {
/* ignore */
}
startRecording();
});
btn.addEventListener('pointerup', (e) => {
e.preventDefault();
if (!pressing) return;
pressing = false;
stopRecording();
});
btn.addEventListener('pointercancel', () => {
pressing = false;
cancelRecording();
});
btn.addEventListener('contextmenu', (e) => e.preventDefault());
window.addEventListener('blur', () => {
if (recording || pressing) {
pressing = false;
cancelRecording();
}
});
list.addEventListener('click', (e) => {
const el = e.target.closest('.vitem');
if (!el) return;
const id = Number(el.dataset.id);
if (!id) return;
if (playingId === id) {
stopAudio();
renderVoice();
return;
}
playVoice(id);
});
renderVoice();
}