Files
mini-browser-games/spectrum-console.html
2026-08-03 21:21:54 +08:00

93 lines
28 KiB
HTML
Raw Permalink 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.

<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="theme-color" content="#163c58">
<meta name="description" content="频谱调音台:十二份信号净化,一款零依赖的离散信号处理浏览器谜题。">
<title>频谱调音台:十二份信号净化</title>
<style>
:root{--bg:#edf3f3;--paper:#fffefa;--ink:#142832;--muted:#62757c;--line:#c3d1d2;--blue:#176b91;--deep:#163c58;--teal:#24735f;--gold:#c58b27;--red:#b4544c;--violet:#665b91;--radius:8px;--shadow:0 10px 25px rgba(16,45,59,.1)}
*{box-sizing:border-box}html{background:var(--bg)}body{margin:0;color:var(--ink);font-family:"Microsoft YaHei","PingFang SC","Noto Sans SC",system-ui,sans-serif;background:linear-gradient(150deg,#edf3f3,#f7f7f0);min-height:100vh}button,select,input{font:inherit}button{cursor:pointer}.shell{width:min(1220px,calc(100vw - 28px));margin:0 auto}.top{padding:24px 0 18px;color:#fff;background:var(--deep);border-bottom:5px solid #edc861}.top-inner{display:flex;justify-content:space-between;gap:24px;align-items:flex-start}.eyebrow{margin:0 0 8px;color:#f5d574;font-size:12px;font-weight:900;letter-spacing:1px}.top h1{margin:0;font-size:clamp(30px,5vw,52px);line-height:1.08}.top p{max-width:700px;margin:10px 0 0;color:#d7e6ec;line-height:1.65;font-size:14px}.top-links{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}.top-links a{display:inline-flex;align-items:center;min-height:40px;padding:0 13px;border:1px solid #8aaebb;border-radius:var(--radius);color:#fff;text-decoration:none;font-weight:900;background:#214e6b}.top-links a.primary{border-color:#f5d574;color:#173246;background:#f5d574}.layout{display:grid;grid-template-columns:280px minmax(0,1fr);gap:16px;padding:20px 0 36px}.panel{border:1px solid var(--line);border-radius:var(--radius);background:rgba(255,254,250,.94);box-shadow:var(--shadow)}.campaign{padding:16px}.panel-title{display:flex;align-items:center;justify-content:space-between;gap:8px;margin:0 0 12px;font-size:16px}.chapter{margin:12px 0 8px;color:var(--muted);font-size:12px;font-weight:900}.contract-list{display:grid;grid-template-columns:1fr 1fr;gap:7px}.contract{min-height:49px;padding:8px;border:1px solid #aebfc1;border-radius:6px;color:var(--ink);background:#f4f8f7;text-align:left}.contract strong{display:block;color:var(--blue);font-size:12px}.contract small{display:block;margin-top:3px;color:var(--muted);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.contract.active{border-color:var(--blue);background:#e3f0f3;box-shadow:inset 0 0 0 2px rgba(23,107,145,.12)}.contract.done{border-left:4px solid var(--teal)}.campaign-foot{margin-top:14px;padding-top:12px;border-top:1px solid var(--line);color:var(--muted);font-size:12px;line-height:1.6}.workbench{display:grid;gap:14px;min-width:0}.signal-panel{padding:16px}.signal-head{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}.signal-head h2{margin:0;font-size:22px}.signal-head p{margin:5px 0 0;color:var(--muted);font-size:13px}.metrics{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}.metric{min-width:86px;padding:8px 10px;border:1px solid var(--line);border-radius:6px;text-align:right;background:#f4f8f6}.metric b{display:block;color:var(--blue);font-size:16px}.metric span{color:var(--muted);font-size:10px;font-weight:900}.wave-wrap{position:relative;margin-top:14px;border:1px solid #9db8bd;border-radius:6px;background:#122f3f;overflow:hidden}.wave-wrap canvas{display:block;width:100%;height:280px}.legend{display:flex;gap:14px;flex-wrap:wrap;margin-top:9px;color:var(--muted);font-size:11px;font-weight:900}.legend i{display:inline-block;width:20px;height:3px;margin-right:5px;vertical-align:middle;border-radius:2px}.input-line{background:#e0a348}.target-line{background:#62c699}.output-line{background:#65b7ef}.frequency{display:grid;grid-template-columns:repeat(8,minmax(0,1fr));gap:5px;align-items:end;height:86px;margin-top:14px;padding:10px 8px 7px;border:1px solid var(--line);border-radius:6px;background:#f1f7f5}.bar{position:relative;min-height:4px;border-radius:4px 4px 2px 2px;background:#63a8c8}.bar.target{background:#62a980}.bar span{position:absolute;top:100%;left:50%;transform:translateX(-50%);margin-top:4px;color:var(--muted);font-size:9px}.modules-panel{padding:16px}.modules-head{display:flex;justify-content:space-between;align-items:flex-start;gap:12px}.modules-head h3{margin:0;font-size:18px}.modules-head p{margin:4px 0 0;color:var(--muted);font-size:12px}.budget{color:var(--gold);font-weight:900;font-size:13px;white-space:nowrap}.slot-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:9px;margin-top:13px}.slot{min-width:0;padding:10px;border:1px solid #afc2c3;border-radius:6px;background:#f5f8f6}.slot-label{display:flex;justify-content:space-between;align-items:center;margin-bottom:7px;color:var(--muted);font-size:11px;font-weight:900}.slot-label button{width:24px;height:24px;padding:0;border:1px solid #c5d2d2;border-radius:5px;color:var(--red);background:#fff}.slot select{width:100%;height:35px;margin-top:5px;padding:0 7px;border:1px solid #aebfc1;border-radius:5px;color:var(--ink);background:#fff}.slot.empty{border-style:dashed;color:var(--muted);text-align:center}.palette{display:flex;gap:7px;flex-wrap:wrap;margin-top:12px}.palette button{min-height:35px;padding:0 10px;border:1px solid #aebfc1;border-radius:6px;color:var(--ink);background:#eaf2f2;font-size:12px;font-weight:900}.palette button:hover{border-color:var(--blue);background:#deedf1}.actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:14px;padding-top:13px;border-top:1px solid var(--line)}.action{min-height:40px;padding:0 13px;border:1px solid #aabec1;border-radius:6px;color:var(--ink);background:#f0f5f2;font-weight:900}.action.primary{border-color:var(--blue);color:#fff;background:var(--blue)}.action.gold{border-color:#b47e1a;color:#fff;background:#b47e1a}.action:disabled{opacity:.45;cursor:not-allowed}.archive{display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:8px;margin-top:12px}.archive input{min-width:0;height:39px;padding:0 10px;border:1px solid #aebfc1;border-radius:6px;color:var(--ink);background:#fff}.archive button{height:39px;padding:0 11px;border:1px solid #aebfc1;border-radius:6px;color:var(--ink);background:#edf4f1;font-weight:900}.status{min-height:27px;margin-top:10px;color:var(--muted);font-size:12px;font-weight:900}.status.good{color:var(--teal)}.status.bad{color:var(--red)}dialog{width:min(520px,calc(100vw - 28px));padding:0;border:1px solid var(--line);border-radius:var(--radius);box-shadow:0 20px 55px rgba(8,30,40,.3);color:var(--ink);background:var(--paper)}dialog::backdrop{background:rgba(10,29,39,.45)}.dialog-inner{padding:20px}.dialog-inner h3{margin:0 0 8px}.dialog-inner p{margin:7px 0;color:var(--muted);line-height:1.6;font-size:13px}.dialog-close{float:right;min-height:36px;padding:0 12px;border:1px solid #aabec1;border-radius:6px;background:#eef4f2;font-weight:900}@media(max-width:900px){.layout{grid-template-columns:1fr}.campaign{order:2}.contract-list{grid-template-columns:repeat(4,minmax(0,1fr))}.slot-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.campaign-foot{display:none}}@media(max-width:620px){.shell{width:calc(100vw - 18px)}.top-inner{display:block}.top-links{justify-content:flex-start;margin-top:16px}.top-links a{flex:1 1 auto;justify-content:center}.layout{padding-top:12px}.signal-panel,.modules-panel,.campaign{padding:12px}.signal-head{display:block}.metrics{justify-content:flex-start;margin-top:10px}.metric{flex:1;min-width:0;text-align:left}.wave-wrap canvas{height:230px}.frequency{gap:3px;height:72px}.slot-grid{grid-template-columns:1fr 1fr;gap:7px}.slot{padding:8px}.archive{grid-template-columns:1fr 1fr}.archive input{grid-column:1/-1}.archive button{width:100%}.contract-list{grid-template-columns:repeat(3,minmax(0,1fr))}.contract{min-height:46px;padding:6px}.contract small{font-size:10px}}
</style>
</head>
<body>
<header class="top"><div class="shell top-inner"><div><p class="eyebrow">SIGNAL LAB · WAVE2</p><h1>频谱调音台</h1><p>十二份信号净化合同。把噪声波形送入有限模块链,让输出同时贴近目标时域和频谱。</p></div><nav class="top-links" aria-label="项目链接"><a class="primary" href="index.html">游戏目录</a><a href="https://github.com/wangzifan396-wzf/mini-browser-games">GitHub</a></nav></div></header>
<main class="shell layout">
<aside class="panel campaign"><h2 class="panel-title"><span>合同台</span><span id="progressText">0 / 12</span></h2><div id="contractList"></div><p class="campaign-foot">橙色线条是输入,绿色线条是目标,亮蓝线条是当前输出。模块顺序和参数都会改变结果。</p></aside>
<section class="workbench">
<section class="panel signal-panel"><div class="signal-head"><div><h2 id="contractTitle">载入合同</h2><p id="contractBrief">正在准备离散采样。</p></div><div class="metrics"><div class="metric"><b id="rmseMetric">--</b><span>均方根误差</span></div><div class="metric"><b id="peakMetric">--</b><span>峰值误差</span></div><div class="metric"><b id="starMetric">--</b><span>当前星级</span></div></div></div><div class="wave-wrap"><canvas id="waveCanvas" width="920" height="280" aria-label="时域波形图"></canvas></div><div class="legend"><span><i class="input-line"></i>输入</span><span><i class="target-line"></i>目标</span><span><i class="output-line"></i>输出</span></div><div class="frequency" id="frequencyBars" aria-label="频谱峰值"></div></section>
<section class="panel modules-panel"><div class="modules-head"><div><h3>模块链</h3><p>每份合同有固定槽位预算。点击模块按钮填入第一个空槽。</p></div><span class="budget" id="budgetText">0 / 0 槽</span></div><div class="slot-grid" id="slotGrid"></div><div class="palette" id="palette"></div><div class="actions"><button class="action primary" id="verifyButton">验收信号</button><button class="action" id="hintButton" title="填入一个参考模块">⌁ 提示</button><button class="action" id="undoButton" title="撤回上一步">↶ 撤回</button><button class="action" id="resetButton" title="清空模块链">⌫ 清空</button></div><div class="status" id="statusText">选择模块后开始调音。</div><div class="archive"><input id="archiveCode" placeholder="WAVE2. 跨设备档案码" aria-label="WAVE2 档案码"><button id="exportButton">导出档案</button><button id="importButton">导入档案</button></div></section>
</section>
</main>
<dialog id="resultDialog"><div class="dialog-inner"><button class="dialog-close" id="closeDialog">关闭</button><h3 id="dialogTitle">信号验收</h3><p id="dialogSummary"></p><p id="dialogDetail"></p></div></dialog>
<script>
(()=>{
const MODULES={
lowpass:{label:"低通",color:"#58a7c7",params:{soft:{label:"柔和",value:.28},firm:{label:"强滤",value:.52}}},
highpass:{label:"高通",color:"#d58d50",params:{soft:{label:"柔和",value:.34},firm:{label:"强滤",value:.62}}},
notch:{label:"带阻",color:"#9276b5",params:{narrow:{label:"窄带",value:.32},wide:{label:"宽带",value:.58}}},
delay:{label:"延迟",color:"#5eaa83",params:{near:{label:"1 拍",value:1},far:{label:"2 拍",value:2}}},
gain:{label:"增益",color:"#bf6d79",params:{trim:{label:"衰减",value:.84},lift:{label:"提升",value:1.16}}},
};
const CONTRACTS=[
{id:"rain",chapter:0,title:"雨棚广播",brief:"低频人声被电流和高次谐波包住。",base:2,noise:19,phase:.2,reference:[['lowpass','soft'],['notch','narrow']]},
{id:"harbor",chapter:0,title:"港口回波",brief:"船台回声拖着一拍延迟,尖锐风啸需要剥离。",base:3,noise:23,phase:1.1,reference:[['highpass','soft'],['delay','near']]},
{id:"metro",chapter:0,title:"地铁报站",brief:"报站声偏高频,轨道低鸣覆盖了清晰度。",base:4,noise:7,phase:2.2,reference:[['highpass','firm'],['gain','lift']]},
{id:"orchard",chapter:1,title:"果园传感",brief:"湿度探头的慢漂移和窄带工频同时出现。",base:1,noise:13,phase:.7,reference:[['notch','wide'],['lowpass','soft'],['gain','lift']]},
{id:"night",chapter:1,title:"夜航灯标",brief:"灯标脉冲需要保留边缘,背景缓慢起伏必须压低。",base:6,noise:3,phase:1.7,reference:[['highpass','soft'],['lowpass','firm'],['delay','near']]},
{id:"museum",chapter:1,title:"展厅回放",brief:"旧录音电平过高且带有细碎高频底噪。",base:2,noise:29,phase:2.9,reference:[['lowpass','firm'],['gain','trim']]},
{id:"forest",chapter:2,title:"林间测站",brief:"风声形成宽带噪声,目标是还原稳定的叶面振动。",base:5,noise:17,phase:.4,reference:[['notch','wide'],['lowpass','firm'],['delay','far']]},
{id:"rocket",chapter:2,title:"试车台遥测",brief:"发动机遥测有明显尖峰,且传感器需要一拍对齐。",base:7,noise:11,phase:1.4,reference:[['notch','narrow'],['delay','far'],['gain','trim']]},
{id:"radio",chapter:2,title:"远距电台",brief:"远距通信先要抬起高频,再修正接收端的电平。",base:3,noise:31,phase:2.4,reference:[['highpass','firm'],['gain','lift'],['notch','narrow']]},
{id:"clinic",chapter:3,title:"心音档案",brief:"心音低频细节珍贵,电源纹波必须被准确切掉。",base:1,noise:9,phase:.9,reference:[['notch','narrow'],['lowpass','soft'],['gain','trim'],['delay','near']]},
{id:"satellite",chapter:3,title:"卫星下行",brief:"下行链路存在宽带抖动、相位拖尾和轻微衰减。",base:8,noise:21,phase:2.1,reference:[['highpass','soft'],['notch','wide'],['delay','near'],['gain','lift']]},
{id:"finale",chapter:3,title:"总控母带",brief:"最后一份母带同时考查净化、对齐与电平控制。",base:5,noise:27,phase:3.0,reference:[['lowpass','soft'],['notch','wide'],['delay','far'],['gain','trim']]},
];
const CHAPTERS=["街区信号","环境测站","远距链路","总控验收"],SAMPLES=96,ARCHIVE="WAVE2",history=[];
let state=null,profile=freshProfile();
const $=id=>document.getElementById(id);
function hash(text){let h=2166136261;for(let i=0;i<text.length;i++){h^=text.charCodeAt(i);h=Math.imul(h,16777619)}return (h>>>0).toString(16).padStart(8,"0")}
function bytesToBase64(text){const bytes=new TextEncoder().encode(text);let binary="";for(const byte of bytes)binary+=String.fromCharCode(byte);return btoa(binary).replace(/=+$/g,"").replace(/\+/g,"-").replace(/\//g,"_")}
function base64ToText(code){const raw=atob(code.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((code.length+3)%4));const bytes=Uint8Array.from(raw,c=>c.charCodeAt(0));return new TextDecoder().decode(bytes)}
function freshProfile(){return{contract:0,stars:Array(CONTRACTS.length).fill(0),bestRmse:Array(CONTRACTS.length).fill(null),clears:Array(CONTRACTS.length).fill(0)}}
function param(module){return MODULES[module[0]]?.params[module[1]]?.value??0}
function normalizeModule(module){if(!module||!MODULES[module.type]||!MODULES[module.type].params[module.param])return null;return{type:module.type,param:module.param}}
function sampleInput(spec){const values=[];for(let i=0;i<SAMPLES;i++){const t=i/SAMPLES;const base=.46*Math.sin(Math.PI*2*spec.base*t)+.2*Math.sin(Math.PI*2*(spec.base+1)*t+.45);const noise=.24*Math.sin(Math.PI*2*spec.noise*t+spec.phase)+.13*Math.cos(Math.PI*2*(spec.noise+5)*t-spec.phase*.5);values.push(base+noise)}return values}
function applyModule(values,module){if(!module)return values.slice();const p=param([module.type,module.param]),out=Array(values.length).fill(0);if(module.type==="lowpass"){out[0]=values[0];for(let i=1;i<values.length;i++)out[i]=p*values[i]+(1-p)*out[i-1]}else if(module.type==="highpass"){out[0]=0;for(let i=1;i<values.length;i++)out[i]=p*(out[i-1]+values[i]-values[i-1])}else if(module.type==="notch"){const strength=p;for(let i=0;i<values.length;i++){const prev=values[i-1]??values[i],next=values[i+1]??values[i];out[i]=values[i]-strength*(values[i]-(prev+next)/2)}}else if(module.type==="delay"){const lag=p;for(let i=0;i<values.length;i++)out[i]=.72*values[i]+.28*(values[i-lag]??values[i])}else if(module.type==="gain"){for(let i=0;i<values.length;i++)out[i]=values[i]*p}return out}
function process(spec,slots){let values=sampleInput(spec);for(const module of slots.filter(Boolean))values=applyModule(values,module);return values}
function targetFor(spec){return process(spec,spec.reference.map(([type,p])=>({type,param:p})))}
function metrics(output,target){let sum=0,peak=0;for(let i=0;i<output.length;i++){const delta=output[i]-target[i];sum+=delta*delta;peak=Math.max(peak,Math.abs(delta))}return{rmse:Math.sqrt(sum/output.length),peak}}
function spectrum(values){const bins=[];for(let k=1;k<=8;k++){let re=0,im=0;for(let n=0;n<values.length;n++){const angle=Math.PI*2*k*n/values.length;re+=values[n]*Math.cos(angle);im-=values[n]*Math.sin(angle)}bins.push(Math.sqrt(re*re+im*im)/values.length)}return bins}
function evaluateSlots(spec,slots,hints=0){const normalized=slots.map(normalizeModule).filter(Boolean);const output=process(spec,normalized),target=targetFor(spec),scores=metrics(output,target),won=scores.rmse<=.0005&&scores.peak<=.001;let stars=won?1:0;if(won&&normalized.length<=spec.maxSlots)stars=2;if(stars===2&&hints===0)stars=3;return{output,target,rmse:scores.rmse,peak:scores.peak,stars,won,used:normalized.length}}
CONTRACTS.forEach(spec=>{spec.maxSlots=spec.reference.length;spec.input=sampleInput(spec);spec.target=targetFor(spec);spec.chapterName=CHAPTERS[spec.chapter]});
function freshState(index=profile.contract){const spec=CONTRACTS[index];return{index,slots:Array(spec.maxSlots).fill(null),hints:0,edits:0,result:null,input:spec.input,target:spec.target,output:spec.input.slice()}}
function snapshot(){return JSON.parse(JSON.stringify({index:state.index,slots:state.slots,hints:state.hints,edits:state.edits}))}
function restore(s){state={...freshState(s.index),slots:s.slots.map(normalizeModule),hints:s.hints,edits:s.edits};refresh()}
function pushHistory(){history.push(snapshot());if(history.length>30)history.shift()}
function setSlot(slot,module){if(slot<0||slot>=state.slots.length)return;pushHistory();state.slots[slot]=normalizeModule(module);state.edits++;state.result=null;refresh()}
function clearSlots(){pushHistory();state.slots.fill(null);state.edits++;state.result=null;refresh()}
function begin(index){profile.contract=Math.max(0,Math.min(CONTRACTS.length-1,index));state=freshState(profile.contract);history.length=0;refresh()}
function hint(){const spec=CONTRACTS[state.index],next=spec.reference[state.slots.findIndex(slot=>!slot)];if(!next)return;pushHistory();const slot=state.slots.findIndex(item=>!item);state.slots[slot]={type:next[0],param:next[1]};state.hints++;state.edits++;state.result=null;refresh();setStatus(`提示已填入第 ${slot+1} 槽。`,"")}
function undo(){const previous=history.pop();if(previous)restore(previous)}
function verify(){const spec=CONTRACTS[state.index],result=evaluateSlots(spec,state.slots,state.hints);state.result=result;profile.clears[state.index]++;if(result.won){profile.stars[state.index]=Math.max(profile.stars[state.index],result.stars);if(profile.bestRmse[state.index]===null||result.rmse<profile.bestRmse[state.index])profile.bestRmse[state.index]=result.rmse;saveProfile();}refresh();showResult(result,spec)}
function saveProfile(){localStorage.setItem("spectrum-console-profile",JSON.stringify(profile))}
function loadProfile(){try{const raw=JSON.parse(localStorage.getItem("spectrum-console-profile")||"null");if(raw?.stars?.length===CONTRACTS.length)profile={...freshProfile(),...raw}}catch{profile=freshProfile()}}
function setStatus(message,tone=""){const node=$("statusText");node.textContent=message;node.className=`status ${tone}`}
function renderContracts(){const host=$("contractList");host.replaceChildren();CHAPTERS.forEach((chapter,chapterIndex)=>{const label=document.createElement("div");label.className="chapter";label.textContent=chapter;host.append(label);const grid=document.createElement("div");grid.className="contract-list";CONTRACTS.filter(item=>item.chapter===chapterIndex).forEach(item=>{const index=CONTRACTS.indexOf(item),button=document.createElement("button");button.className=`contract${index===state.index?" active":""}${profile.stars[index]>=3?" done":""}`;button.dataset.index=index;button.innerHTML=`<strong>${String(index+1).padStart(2,"0")} · ${item.title}</strong><small>${profile.stars[index]?"★".repeat(profile.stars[index])+" · ":""}${item.reference.length} 模块</small>`;grid.append(button)});host.append(grid)});$("progressText").textContent=`${profile.stars.filter(Boolean).length} / ${CONTRACTS.length}`}
function renderSlots(){const host=$("slotGrid");host.replaceChildren();state.slots.forEach((module,index)=>{const card=document.createElement("div");card.className=`slot${module?"":" empty"}`;const label=document.createElement("div");label.className="slot-label";label.innerHTML=`<span>槽 ${index+1}</span>`;if(module){const remove=document.createElement("button");remove.type="button";remove.dataset.remove=index;remove.textContent="×";remove.title="移除模块";label.append(remove)}card.append(label);const type=document.createElement("select");type.dataset.type=index;type.setAttribute("aria-label",`槽 ${index+1} 模块`);type.innerHTML=`<option value="">${module?"选择模块":"空槽"}</option>`+Object.entries(MODULES).map(([key,item])=>`<option value="${key}"${module?.type===key?" selected":""}>${item.label}</option>`).join("");card.append(type);const selectedType=module?.type||"lowpass",params=MODULES[selectedType].params,param=document.createElement("select");param.dataset.param=index;param.setAttribute("aria-label",`槽 ${index+1} 参数`);param.innerHTML=Object.entries(params).map(([key,item])=>`<option value="${key}"${module?.param===key?" selected":""}>${item.label}</option>`).join("");param.disabled=!module;card.append(param);host.append(card)});$("budgetText").textContent=`${state.slots.filter(Boolean).length} / ${CONTRACTS[state.index].maxSlots} 槽`}
function renderPalette(){const host=$("palette");host.replaceChildren();Object.entries(MODULES).forEach(([type,module])=>{const button=document.createElement("button");button.dataset.add=type;button.textContent=`+ ${module.label}`;host.append(button)})}
function draw(){const canvas=$("waveCanvas"),ctx=canvas.getContext("2d"),width=canvas.width,height=canvas.height;ctx.clearRect(0,0,width,height);ctx.fillStyle="#122f3f";ctx.fillRect(0,0,width,height);ctx.strokeStyle="rgba(211,235,238,.13)";ctx.lineWidth=1;for(let i=1;i<8;i++){const x=i*width/8;ctx.beginPath();ctx.moveTo(x,0);ctx.lineTo(x,height);ctx.stroke()}for(let i=1;i<5;i++){const y=i*height/5;ctx.beginPath();ctx.moveTo(0,y);ctx.lineTo(width,y);ctx.stroke()}const drawLine=(values,color,lineWidth)=>{ctx.strokeStyle=color;ctx.lineWidth=lineWidth;ctx.beginPath();values.forEach((value,index)=>{const x=index*(width-20)/(values.length-1)+10,y=height/2-value*(height*.38);index?ctx.lineTo(x,y):ctx.moveTo(x,y)});ctx.stroke()};drawLine(state.input,"#e0a348",1.5);drawLine(state.target,"#62c699",2);drawLine(state.output,"#65b7ef",2.2);const outputSpectrum=spectrum(state.output),targetSpectrum=spectrum(state.target),bars=$("frequencyBars");bars.replaceChildren();outputSpectrum.forEach((value,index)=>{const bar=document.createElement("div");bar.className="bar";bar.style.height=`${Math.max(4,Math.min(100,value*340))}%`;bar.title=`${index+1} · 输出 ${value.toFixed(3)} / 目标 ${targetSpectrum[index].toFixed(3)}`;const span=document.createElement("span");span.textContent=`${index+1}f`;bar.append(span);bars.append(bar)})}
function refresh(){const spec=CONTRACTS[state.index];state.input=spec.input;state.target=spec.target;state.output=process(spec,state.slots.filter(Boolean));$("contractTitle").textContent=`${String(state.index+1).padStart(2,"0")} · ${spec.title}`;$("contractBrief").textContent=spec.brief;const result=evaluateSlots(spec,state.slots,state.hints);$("rmseMetric").textContent=result.rmse.toFixed(4);$("peakMetric").textContent=result.peak.toFixed(4);$("starMetric").textContent=result.stars?"★".repeat(result.stars):"—";renderContracts();renderSlots();renderPalette();draw()}
function showResult(result,spec){$("dialogTitle").textContent=result.won?`${spec.title} · 验收通过`:`${spec.title} · 需要重调`;$("dialogSummary").textContent=result.won?`获得 ${result.stars} 星,使用 ${result.used} 个模块,均方根误差 ${result.rmse.toFixed(4)}。`:`均方根误差 ${result.rmse.toFixed(4)},峰值误差 ${result.peak.toFixed(4)};继续调整模块顺序或参数。`;$("dialogDetail").textContent=result.won?"输出已写入本地进度,可以切换下一份合同。":"目标同时约束时域与频谱,单看一条曲线还不够。";$("resultDialog").showModal()}
function encodeArchive(){const payload={contract:profile.contract,stars:profile.stars,bestRmse:profile.bestRmse,clears:profile.clears};const body=JSON.stringify(payload);return `${ARCHIVE}.${bytesToBase64(JSON.stringify({...payload,check:hash(body)}))}`}
function decodeArchive(code){if(typeof code!=="string"||!code.startsWith(`${ARCHIVE}.`))throw Error("档案前缀错误");const payload=JSON.parse(base64ToText(code.slice(ARCHIVE.length+1))),{check,...data}=payload;if(hash(JSON.stringify(data))!==check)throw Error("档案校验失败");if(!Array.isArray(data.stars)||data.stars.length!==CONTRACTS.length)throw Error("档案内容错误");return data}
function exportArchive(){const code=encodeArchive();$("archiveCode").value=code;setStatus("档案已生成,可复制到另一台设备。","good")}
function importArchive(){try{const data=decodeArchive($("archiveCode").value.trim());profile={...freshProfile(),...data};saveProfile();begin(profile.contract);setStatus("档案导入成功。","good")}catch(error){setStatus(`导入失败:${error.message}`,"bad")}}
$("contractList").addEventListener("click",event=>{const button=event.target.closest("[data-index]");if(button)begin(Number(button.dataset.index))});$("palette").addEventListener("click",event=>{const button=event.target.closest("[data-add]");if(!button)return;const slot=state.slots.findIndex(item=>!item);if(slot<0){setStatus("当前合同的槽位已满。","bad");return}setSlot(slot,{type:button.dataset.add,param:Object.keys(MODULES[button.dataset.add].params)[0]})});$("slotGrid").addEventListener("click",event=>{const remove=event.target.closest("[data-remove]");if(remove){setSlot(Number(remove.dataset.remove),null)}});$("slotGrid").addEventListener("change",event=>{const index=Number(event.target.dataset.type??event.target.dataset.param);if(!Number.isInteger(index))return;if(event.target.dataset.type!==undefined){const type=event.target.value;if(!type){setSlot(index,null);return}setSlot(index,{type,param:state.slots[index]?.param&&MODULES[type].params[state.slots[index].param]?state.slots[index].param:Object.keys(MODULES[type].params)[0]})}else setSlot(index,{type:state.slots[index].type,param:event.target.value})});$("verifyButton").addEventListener("click",verify);$("hintButton").addEventListener("click",hint);$("undoButton").addEventListener("click",undo);$("resetButton").addEventListener("click",clearSlots);$("exportButton").addEventListener("click",exportArchive);$("importButton").addEventListener("click",importArchive);$("closeDialog").addEventListener("click",()=>$("resultDialog").close());
loadProfile();state=freshState(profile.contract);window.__spectrumConsoleTest={MODULES,contracts:CONTRACTS,chapters:CHAPTERS,getState:()=>JSON.parse(JSON.stringify(state)),freshProfile,begin,setSlots:(slots)=>{history.length=0;state.slots=slots.map(normalizeModule).slice(0,CONTRACTS[state.index].maxSlots);while(state.slots.length<CONTRACTS[state.index].maxSlots)state.slots.push(null);state.result=null;refresh()},evaluate:(index,slots)=>evaluateSlots(CONTRACTS[index],slots,0),validateContent:()=>{const references=CONTRACTS.map((spec,index)=>{const result=evaluateSlots(spec,spec.reference.map(([type,param])=>({type,param})),0);return{id:spec.id,won:result.won,stars:result.stars,rmse:result.rmse,peak:result.peak,modules:spec.reference.length}});return{contracts:CONTRACTS.length,chapters:CHAPTERS.length,moduleTypes:Object.keys(MODULES).length,samples:SAMPLES,uniqueSources:new Set(CONTRACTS.map(item=>item.id)).size,referenceWins:references.filter(item=>item.won).length,referenceThreeStars:references.filter(item=>item.stars===3).length,references}},encodeArchive:()=>encodeArchive(),decodeArchive,profile:()=>JSON.parse(JSON.stringify(profile))};refresh();
})();
</script>
</body>
</html>