feat(ai): 教练人格(务实/严厉/温柔/毒舌/老棋手)+ 语音朗读 + 赛后 AI 复盘(三个游戏各自生成复盘摘要)

This commit is contained in:
personal82555 committed 2026-10-08 15:51:31 +08:00
1 parent ea89899221
commit d782c1a1ae
7 files changed
+116 -17

No files matched your search

+8 -8
View File
@@ -19,14 +19,14 @@
<main id="view"></main>
<script src="/js/gomoku.js?v=52"></script>
<script src="/js/chess.js?v=52"></script>
<script src="/js/chessAI.js?v=52"></script>
<script src="/js/junqi.js?v=52"></script>
<script src="/js/gomoku_client.js?v=52"></script>
<script src="/js/chess_client.js?v=52"></script>
<script src="/js/junqi_client.js?v=52"></script>
<script src="/js/common.js?v=52"></script>
<script src="/js/gomoku.js?v=53"></script>
<script src="/js/chess.js?v=53"></script>
<script src="/js/chessAI.js?v=53"></script>
<script src="/js/junqi.js?v=53"></script>
<script src="/js/gomoku_client.js?v=53"></script>
<script src="/js/chess_client.js?v=53"></script>
<script src="/js/junqi_client.js?v=53"></script>
<script src="/js/common.js?v=53"></script>
<script>
const views = {
chess: () => gameLobby('chess','象棋','🐟 楚河汉界,红先黑后,工作间隙杀一盘'),
+9
View File
@@ -202,6 +202,15 @@ function redoFromMoves() {
// —— 存档 / 恢复 ——
window.GAMEHOOKS = window.GAMEHOOKS || {};
GAMEHOOKS.chess = {
reviewPrompt: function () {
const res = cg && cg.moves.length
? (cg.inCheck ? '' : '') : '';
let outcome = '本局结束';
try { if (cg && !cg.allLegal(cg.redTurn ? 'r' : 'b').length) outcome = (cg.redTurn ? '红方' : '黑方') + '无棋可走(被将死/困毙)'; } catch (e) {}
const last = (cg && cg.moves ? cg.moves.slice(-8) : []).map((m, i) => '第' + (cg.moves.length - Math.min(8, cg.moves.length) + i + 1) + '手:(' + m[0] + ',' + m[1] + ')→(' + m[2] + ',' + m[3] + ')').join(';');
return '【象棋复盘】结果:' + outcome + '。总手数:' + (cg ? cg.moves.length : 0) + '。\n最后几手:' + (last || '无') + '\n' + (aiBoardDesc ? aiBoardDesc() : '') ;
},
started: function () { return !!cg; },
inProgress: function () { return !!(cg && cg.moves.length > 0 && !cg.over && !window.__gameOver); },
serialize: function () {
+51 -2
View File
@@ -102,6 +102,18 @@ function aiSettings() {
<button class="btn" type="button" onclick="toggleKeyVisible()" id="ai-key-btn" style="padding:9px 12px;white-space:nowrap">👁 显示</button>
</div>
<input id="ai-model" placeholder="模型名 例:deepseek-v4.1-flash" value="${cfg.model || 'deepseek-v4.1-flash'}">
<div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;font-size:13px">
<label style="color:#555">🎭 教练人格
<select id="ai-persona" style="font-size:13px;padding:5px 8px">
<option value="default">务实教练(默认)</option>
<option value="strict">严厉教练</option>
<option value="gentle">温柔启蒙</option>
<option value="savage">毒舌损友</option>
<option value="master">老棋手(江湖气)</option>
</select>
</label>
<label style="color:#555"><input type="checkbox" id="ai-voice"> 🔊 语音朗读建议</label>
</div>
<div><button class="btn primary" onclick="aiSave()">保存并启用</button>
<button class="btn" onclick="aiTestConnection()">🔌 测试连接</button>
<button class="btn" onclick="document.getElementById('ai-set').remove()">关闭</button></div>
@@ -146,7 +158,8 @@ function toggleKeyVisible() {
}
window.toggleKeyVisible = toggleKeyVisible;
function aiSave() {
saveAICfg({ baseUrl: document.getElementById('ai-url').value.trim(), apiKey: document.getElementById('ai-key').value.trim(), model: document.getElementById('ai-model').value.trim() });
const ps = document.getElementById('ai-persona'), vc = document.getElementById('ai-voice');
saveAICfg({ baseUrl: document.getElementById('ai-url').value.trim(), apiKey: document.getElementById('ai-key').value.trim(), model: document.getElementById('ai-model').value.trim(), persona: ps ? ps.value : 'default', voice: !!(vc && vc.checked) });
const b = document.getElementById('ai-set'); if (b) b.remove();
gameRestart();
}
@@ -203,15 +216,49 @@ async function aiCoach() {
if (btn) { btn.disabled = true; btn.innerText = '🤖 思考中…'; }
try {
const resp = await fetch('/api/ai-hint', { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ baseUrl: cfg.baseUrl, apiKey: cfg.apiKey, model: cfg.model, prompt: aiBoardDesc() }) });
body: JSON.stringify({ baseUrl: cfg.baseUrl, persona: cfg.persona || 'default', task: 'hint', apiKey: cfg.apiKey, model: cfg.model, prompt: aiBoardDesc() }) });
const j = await resp.json();
if (box) box.innerText = '💡 AI 教练:' + (j.hint || ('出错了:' + j.error));
if (j.hint) speakHint(j.hint, cfg);
} catch (e) {
if (box) box.innerText = '💡 AI 教练连接失败:' + e.message;
}
if (btn) { btn.disabled = false; btn.innerText = '🤖 AI 教我走'; }
}
// —— 语音朗读(浏览器自带,无需额外服务) ——
function speakHint(text, cfg) {
try {
if (!(cfg || getAICfg()).voice) return;
if (!('speechSynthesis' in window)) return;
const clean = String(text).replace(/[「」【】*#`]/g, '').slice(0, 120);
speechSynthesis.cancel();
const u = new SpeechSynthesisUtterance(clean);
u.lang = 'zh-CN'; u.rate = 1.05; u.pitch = 1.0;
speechSynthesis.speak(u);
} catch (e) {}
}
window.speakHint = speakHint;
// —— 赛后 AI 复盘 ——
function aiReview() {
const cfg = getAICfg();
if (!cfg.baseUrl || !cfg.model) { aiSettings(); return; }
const key = curGameKey();
const h = (window.GAMEHOOKS || {})[key];
const box = document.getElementById('review-box');
if (box) { box.style.display = 'block'; box.innerText = '🧠 AI 正在复盘这盘棋…'; }
let prompt = '';
try { prompt = (h && typeof h.reviewPrompt === 'function') ? h.reviewPrompt() : ''; } catch (e) {}
if (!prompt) prompt = '本局已结束,请给出通用改进建议。';
fetch('/api/ai-hint', { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ baseUrl: cfg.baseUrl, persona: cfg.persona || 'default', task: 'review', prompt }) })
.then(r => r.json()).then(j => {
if (box) box.innerText = j.hint ? ('🧠 AI 复盘(' + (cfg.persona === 'savage' ? '毒舌' : cfg.persona === 'strict' ? '严厉' : cfg.persona === 'gentle' ? '温柔' : cfg.persona === 'master' ? '老棋手' : '教练') + '):\n' + j.hint) : ('复盘失败:' + j.error);
if (j.hint) speakHint(j.hint, cfg);
}).catch(e => { if (box) box.innerText = '复盘连接失败:' + e.message; });
}
window.aiReview = aiReview;
function toggleAuto() {
const on = localStorage.getItem('fnos_ai_auto') !== '1';
localStorage.setItem('fnos_ai_auto', on ? '1' : '0');
@@ -242,7 +289,9 @@ function gameResultPopup(won, title, detail) {
<div style="font-size:22px;font-weight:bold;margin:6px 0">${title}</div>
${detail ? `<div style="color:#666;margin-bottom:10px">${detail}</div>` : ''}
<div><button class="btn primary" onclick="gameRestart()">⟳ 再来一局</button>
<button class="btn" onclick="aiReview()">🧠 AI 复盘这盘棋</button>
<button class="btn" onclick="document.getElementById('result-modal').remove()">关闭</button></div>
<div id="review-box" style="display:none;text-align:left;margin-top:12px;padding:10px 12px;background:#f7f9fc;border:1px solid #dde5f0;border-radius:8px;font-size:14px;line-height:1.8;color:#333;white-space:pre-wrap;max-height:40vh;overflow:auto"></div>
</div>`;
document.getElementById('view').prepend(box);
}
+13 -3
View File
@@ -110,9 +110,12 @@ function gokEnd() {
const r = gk.win5[0][0], c = gk.win5[0][1];
const blackWin = gk.B[r][c] === 1;
setStatus('gok-st', '🎉 ' + (blackWin ? '黑方胜!' : '白方胜!'));
if (blackWin) { recordGame({ game: 'gomoku', result: 'win', dur: durTxt, steps: gk.seq.length }); gameResultPopup(true, '🏆 黑方胜!', '五连达成 · 用时 ' + durTxt + ' · 共 ' + gk.seq.length + ' 手'); }
else { recordGame({ game: 'gomoku', result: 'lose', dur: durTxt, steps: gk.seq.length }); gameResultPopup(false, '💔 白方胜', 'AI 先连成五子 · 用时 ' + durTxt); }
} else { setStatus('gok-st', '平局'); recordGame({ game: 'gomoku', result: 'draw', dur: fmtDur(gameDurationSec()), steps: gk.seq.length }); gameResultPopup(null, '🤝 平局', ''); }
if (blackWin) { recordGame({ game: 'gomoku', result: 'win', dur: durTxt, steps: gk.seq.length }); window.__lastResult = 'win';
gameResultPopup(true, '🏆 黑方胜!', '五连达成 · 用时 ' + durTxt + ' · 共 ' + gk.seq.length + ' 手'); }
else { recordGame({ game: 'gomoku', result: 'lose', dur: durTxt, steps: gk.seq.length }); window.__lastResult = 'lose';
gameResultPopup(false, '💔 白方胜', 'AI 先连成五子 · 用时 ' + durTxt); }
} else { setStatus('gok-st', '平局'); recordGame({ game: 'gomoku', result: 'draw', dur: fmtDur(gameDurationSec()), steps: gk.seq.length }); window.__lastResult = 'draw';
gameResultPopup(null, '🤝 平局', ''); }
return true;
}
window.gomokuUndo = function() {
@@ -133,6 +136,13 @@ window.gomokuUndo = function() {
// —— 存档 / 恢复 ——
window.GAMEHOOKS = window.GAMEHOOKS || {};
GAMEHOOKS.gomoku = {
reviewPrompt: function () {
const seq = (gk && gk.seq) ? gk.seq : [];
const last = seq.slice(-10).map((p, i) => '第' + (seq.length - Math.min(10, seq.length) + i + 1) + '子:(' + p[0] + ',' + p[1] + ')').join(';');
const res = (window.__lastResult === 'win') ? '黑方(玩家)胜' : (window.__lastResult === 'lose' ? '白方(AI)胜' : '结束/平局');
return '【五子棋复盘】结果:' + res + '。总落子:' + seq.length + ' 子(黑先)。\n最后几手:' + (last || '无') + '\n请点评关键失误与改进方向。';
},
started: function () { return !!gk; },
inProgress: function () { return !!(gk && gk.seq.length > 0 && !gk.over && !window.__gameOver); },
serialize: function () {
+7
View File
@@ -268,6 +268,13 @@ window.junqiUndo = function() {
// —— 存档 / 恢复 ——
window.GAMEHOOKS = window.GAMEHOOKS || {};
GAMEHOOKS.junqi = {
reviewPrompt: function () {
const hist = (jq && jq._hist) ? jq._hist : [];
const steps = hist.slice(-12).map(x => (x.type === 'flip' ? '翻子' : '走子/吃子') + '(' + x.r + ',' + x.c + ')' + (x.tr != null ? '→(' + x.tr + ',' + x.tc + ')' : '')).join(';');
const res = jq && jq.flagTaken ? ('军旗被' + (jq.flagTaken === 'r' ? '蓝方' : '红方') + '吃掉') : '结束';
return '【军棋(陆战棋翻棋)复盘】结果:' + res + '。总步数:' + (hist.length) + '。\n最后几步:' + (steps || '无') + '\n请点评开局翻子节奏、行营抢占与吃子取舍。';
},
started: function () { return !!jq; },
inProgress: function () { return !!(jq && (jq._hist || []).length > 0 && !jq.winner() && !window.__gameOver); },
serialize: function () {
+17 -4
View File
@@ -128,18 +128,31 @@ const CTJ = { 'Content-Type': 'application/json; charset=utf-8' };
async function aiHintAPI(req, res, body) {
try {
const { baseUrl, apiKey, model, prompt } = JSON.parse(body);
const { baseUrl, apiKey, model, prompt, persona, task } = JSON.parse(body);
if (!baseUrl || !model || !prompt) { res.writeHead(400, CTJ); return res.end(JSON.stringify({ error: '缺少 baseUrl/model/prompt' })); }
// 教练人格:同一句建议,语气不同,趣味和粘性差别很大
const PERSONA = {
default: '你是一位中文棋类教练,讲解直接、务实。',
strict: '你是一位严厉的棋类教练,说话简短有力、一针见血,会直接指出错误,但始终是为了让学员进步。',
gentle: '你是一位温柔的棋类启蒙老师,语气亲切鼓励,先肯定再做提示,绝不用打击式语言。',
savage: '你是一位毒舌损友教练,会用调侃吐槽的口吻点评(但不下流、不侮辱),吐槽之后再给出真正有用的建议。',
master: '你是一位老棋手,说话稳、有江湖气,喜欢用象棋俗语(如“马走日、炮翻山”“车正永无沉底月”)来讲解。'
};
const who = PERSONA[persona] || PERSONA.default;
const isReview = task === 'review';
const sys = isReview
? who + '用户会给你一盘刚结束的棋局信息,请用 3 句话做复盘:①胜负关键在哪 ②双方最大的失误(点出具体位置或阶段)③一句最有用的改进建议。不要客套、不要重复棋谱。'
: who + '用户给出棋局描述,请用一句话(50字以内)直接告诉用户下一步怎么走,指出具体位置和理由。只输出建议本身,不要输出思考过程、不要客套。';
const url = baseUrl.replace(/\/$/, '') + '/chat/completions';
const payload = {
model,
stream: false,
messages: [
{ role: 'system', content: '你是一位中文棋类教练。用户给出棋局描述,请用一句话(50字以内)直接告诉用户下一步怎么走,指出具体位置和理由。只输出建议本身,不要输出思考过程、不要客套。' },
{ role: 'system', content: sys },
{ role: 'user', content: prompt }
],
max_tokens: 512,
temperature: 0.6
max_tokens: isReview ? 700 : 512,
temperature: isReview ? 0.75 : 0.6
};
const u = new URL(url);
const mod = u.protocol === 'https:' ? require('https') : require('http');
+11
View File
@@ -0,0 +1,11 @@
const http = require('http');
http.createServer((req, res) => {
let b = ''; req.on('data', d => b += d);
req.on('end', () => {
const j = JSON.parse(b || '{}');
const sys = (j.messages || []).filter(m => m.role === 'system').map(m => m.content).join(' ');
const user = (j.messages || []).filter(m => m.role === 'user').map(m => m.content).join(' ');
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ choices: [{ message: { content: 'SYSTEM=' + sys.slice(0, 60) + ' || MAXTOK=' + j.max_tokens + ' || USER=' + user.slice(0, 40) }, finish_reason: 'stop' }] }));
});
}).listen(7097, () => console.log('echo up'));