Files
mini-browser-games/lockmaster-shift.html
2026-08-06 18:03:09 +08:00

95 lines
34 KiB
HTML

<!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="#184d5a">
<meta name="description" content="潮门值班:十二班船闸调度,一款关于水位、舱容、时限与能耗的零依赖浏览器策略谜题。">
<title>潮门值班:十二班船闸调度</title>
<style>
:root{--ink:#15313a;--muted:#667a7e;--paper:#fffefa;--wash:#eef4f2;--line:#b9cbc8;--deep:#184d5a;--blue:#176b91;--teal:#24735f;--gold:#c18a22;--red:#b64f49;--radius:8px;--shadow:0 10px 28px rgba(20,55,60,.11)}*{box-sizing:border-box}html{background:#eaf1ef}body{margin:0;min-height:100vh;color:var(--ink);font-family:"Microsoft YaHei","PingFang SC","Noto Sans SC",system-ui,sans-serif;background:linear-gradient(145deg,#eaf1ef,#f7f6ed)}button,select,input{font:inherit}button{cursor:pointer}.shell{width:min(1240px,calc(100vw - 28px));margin:0 auto}.top{padding:22px 0 18px;border-bottom:5px solid #e6bd55;color:#fff;background:var(--deep)}.top-inner{display:flex;align-items:flex-start;justify-content:space-between;gap:22px}.eyebrow{margin:0 0 6px;color:#f0d176;font-size:12px;font-weight:900;letter-spacing:1px}.top h1{margin:0;font-size:clamp(29px,5vw,50px);line-height:1.08}.top p{max-width:740px;margin:9px 0 0;color:#d8eaeb;font-size:14px;line-height:1.6}.top-links{display:flex;gap:8px;flex-wrap:wrap}.top-links a{display:inline-flex;align-items:center;justify-content:center;min-height:40px;padding:0 13px;border:1px solid #8eb4bc;border-radius:var(--radius);color:#fff;text-decoration:none;font-weight:900;background:#245f6c}.top-links a.primary{border-color:#f0d176;color:#17333a;background:#f0d176}.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,.96);box-shadow:var(--shadow)}.campaign{padding:16px}.panel-title{display:flex;justify-content:space-between;gap:10px;margin:0 0 11px;font-size:17px}.chapter{margin:12px 0 7px;color:var(--muted);font-size:12px;font-weight:900}.shift-grid{display:grid;grid-template-columns:1fr 1fr;gap:7px}.shift{min-height:51px;padding:8px;border:1px solid #afc2bf;border-radius:6px;color:var(--ink);text-align:left;background:#f2f7f5}.shift strong{display:block;color:var(--blue);font-size:12px}.shift small{display:block;margin-top:4px;color:var(--muted);font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.shift.active{border-color:var(--blue);background:#e2f0f2;box-shadow:inset 0 0 0 2px rgba(23,107,145,.12)}.shift.done{border-left:4px solid var(--teal)}.notice{margin:14px 0 0;padding-top:12px;border-top:1px solid var(--line);color:var(--muted);font-size:11px;line-height:1.55}.work{display:grid;gap:14px;min-width:0}.scene-panel{padding:16px}.scene-head{display:flex;justify-content:space-between;align-items:flex-start;gap:14px}.scene-head h2{margin:0;font-size:22px}.scene-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:82px;padding:8px 10px;border:1px solid var(--line);border-radius:6px;text-align:right;background:#f3f7f4}.metric b{display:block;color:var(--blue);font-size:16px}.metric span{color:var(--muted);font-size:10px;font-weight:900}.canvas-wrap{margin-top:13px;border:1px solid #8aa8aa;border-radius:6px;overflow:hidden;background:#153a43}.canvas-wrap canvas{display:block;width:100%;height:300px}.manifest{display:grid;grid-template-columns:1fr 1.25fr 1fr;gap:9px;margin-top:10px}.berth{min-width:0;padding:9px;border:1px solid var(--line);border-radius:6px;background:#f4f7f4}.berth h3{display:flex;justify-content:space-between;gap:8px;margin:0 0 7px;font-size:12px}.berth h3 span{color:var(--muted);font-weight:700}.boats{display:flex;gap:6px;flex-wrap:wrap;min-height:38px}.boat{min-height:38px;padding:5px 8px;border:1px solid #9eb8b7;border-radius:5px;color:var(--ink);background:#fff;font-size:11px;font-weight:900}.boat small{display:block;color:var(--muted);font-size:9px;font-weight:700}.boat.fragile{border-color:#c59143;background:#fff7df}.boat.ready{border-color:var(--teal);box-shadow:inset 0 -3px 0 rgba(36,115,95,.18)}.empty{color:#89999b;font-size:11px;line-height:38px}.control-panel{padding:16px}.control-head{display:flex;justify-content:space-between;gap:12px;align-items:flex-start}.control-head h3{margin:0;font-size:18px}.control-head p{margin:5px 0 0;color:var(--muted);font-size:12px}.goal{color:var(--gold);font-size:12px;font-weight:900;text-align:right}.controls{display:grid;grid-template-columns:1fr 1fr minmax(155px,1.1fr);gap:10px;margin-top:13px}.control-group{padding:10px;border:1px solid var(--line);border-radius:6px;background:#f4f7f4}.control-group h4{margin:0 0 8px;color:var(--muted);font-size:11px}.button-row{display:flex;gap:7px}.action{min-height:42px;padding:0 12px;border:1px solid #a4bab8;border-radius:6px;color:var(--ink);background:#fff;font-weight:900}.button-row .action{flex:1}.action.primary{border-color:var(--blue);color:#fff;background:var(--blue)}.action.warn{border-color:#c59646;background:#fff6da}.action:disabled{cursor:not-allowed;opacity:.46}.pump-row{display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:7px}.pump-row select{min-width:0;height:42px;padding:0 8px;border:1px solid #a4bab8;border-radius:6px;color:var(--ink);background:#fff}.secondary-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}.status{min-height:28px;margin-top:10px;color:var(--muted);font-size:12px;font-weight:900}.status.good{color:var(--teal)}.status.bad{color:var(--red)}.log{max-height:96px;margin-top:8px;padding:8px;border-left:3px solid #98b1af;color:var(--muted);background:#f4f7f4;font:11px/1.55 ui-monospace,"Microsoft YaHei",monospace;overflow:auto}.archive{display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:8px;margin-top:11px}.archive input{min-width:0;height:39px;padding:0 10px;border:1px solid #a4bab8;border-radius:6px;background:#fff}.archive button{height:39px;padding:0 11px;border:1px solid #a4bab8;border-radius:6px;background:#edf4f0;font-weight:900}dialog{width:min(520px,calc(100vw - 28px));padding:0;border:1px solid var(--line);border-radius:var(--radius);color:var(--ink);background:var(--paper);box-shadow:0 20px 55px rgba(8,30,35,.3)}dialog::backdrop{background:rgba(8,28,33,.45)}.dialog-inner{padding:20px}.dialog-inner h3{margin:0 0 8px}.dialog-inner p{margin:7px 0;color:var(--muted);font-size:13px;line-height:1.6}.dialog-close{float:right;min-height:36px;padding:0 12px;border:1px solid #a4bab8;border-radius:6px;background:#edf4f0;font-weight:900}@media(max-width:930px){.layout{grid-template-columns:1fr}.campaign{order:2}.shift-grid{grid-template-columns:repeat(4,minmax(0,1fr))}.notice{display:none}}@media(max-width:650px){.shell{width:calc(100vw - 18px)}.top-inner{display:block}.top-links{margin-top:15px}.top-links a{flex:1}.layout{padding-top:12px}.scene-panel,.control-panel,.campaign{padding:11px}.scene-head{display:block}.metrics{justify-content:flex-start;margin-top:9px}.metric{flex:1;min-width:0;text-align:left}.canvas-wrap canvas{height:225px}.manifest{grid-template-columns:1fr 1fr}.berth.chamber{grid-column:1/-1;grid-row:1}.controls{grid-template-columns:1fr}.secondary-actions .action{flex:1;min-width:90px}.archive{grid-template-columns:1fr 1fr}.archive input{grid-column:1/-1}.archive button{width:100%}.shift-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.shift{min-height:47px;padding:6px}.shift small{font-size:9px}.boat{min-height:42px}.control-head{display:block}.goal{margin-top:7px;text-align:left}}
</style>
</head>
<body>
<header class="top"><div class="shell top-inner"><div><p class="eyebrow">LOCK OPERATIONS · LOCK2</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="shiftList"></div><p class="notice">规则抽象自船闸的水位校平与闭闸升降原则,仅用于益智玩法,不用于真实航运、闸控或安全决策。</p></aside>
<section class="work">
<section class="panel scene-panel"><div class="scene-head"><div><h2 id="shiftTitle">载入值班</h2><p id="shiftBrief">正在核对潮位尺。</p></div><div class="metrics"><div class="metric"><b id="timeMetric">0</b><span>调度时刻</span></div><div class="metric"><b id="energyMetric">0</b><span>泵站能耗</span></div><div class="metric"><b id="levelMetric">L0</b><span>闸室水位</span></div></div></div><div class="canvas-wrap"><canvas id="lockCanvas" width="920" height="300" aria-label="船闸水位与船只示意"></canvas></div><div class="manifest"><section class="berth" id="westBerth"><h3>西岸待闸 <span id="westLevelText">L0</span></h3><div class="boats" id="westBoats"></div></section><section class="berth chamber"><h3>闸室载荷 <span id="capacityText">0 / 0</span></h3><div class="boats" id="chamberBoats"></div></section><section class="berth" id="eastBerth"><h3>东岸待闸 <span id="eastLevelText">L0</span></h3><div class="boats" id="eastBoats"></div></section></div></section>
<section class="panel control-panel"><div class="control-head"><div><h3>中央闸控台</h3><p>开闸前必须校平对应岸水位;泵水前必须关闭两侧闸门。</p></div><div class="goal" id="goalText">预算载入中</div></div><div class="controls"><div class="control-group"><h4>闸门</h4><div class="button-row"><button class="action" id="westGate">西闸</button><button class="action" id="eastGate">东闸</button></div></div><div class="control-group"><h4>泵水模式</h4><div class="pump-row"><select id="pumpMode" aria-label="泵水模式"><option value="eco">节能泵 · 慢</option><option value="normal" selected>标准泵 · 平衡</option><option value="fast">急泵 · 高耗</option></select><button class="action" id="pumpDown" title="水位下降">↓</button><button class="action" id="pumpUp" title="水位上升">↑</button></div></div><div class="control-group"><h4>交班</h4><div class="button-row"><button class="action primary" id="verifyButton">验收</button><button class="action" id="waitButton">等待</button></div></div></div><div class="secondary-actions"><button class="action warn" id="hintButton">⌁ 调度提示</button><button class="action" id="undoButton" title="撤回上一步">↶ 撤回</button><button class="action" id="resetButton" title="重置本班">⌫ 重置</button></div><div class="status" id="statusText">选择闸门开始调度。</div><div class="log" id="actionLog">值班记录尚为空。</div><div class="archive"><input id="archiveCode" placeholder="LOCK2. 跨设备档案码" aria-label="LOCK2 档案码"><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 ARCHIVE="LOCK2",CHAPTERS=["内河学徒班","港湾合流班","风暴优先班","总闸联合班"],SIDE_NAME={W:"西岸",E:"东岸"},KIND={mail:["邮袋","邮"],food:["冷藏","冷"],glass:["玻璃","璃"],steel:["工程","工"],rescue:["救援","援"],timber:["木料","木"]},MODES={eco:{label:"节能泵",time:3,energy:2,fragile:true},normal:{label:"标准泵",time:2,energy:4,fragile:true},fast:{label:"急泵",time:1,energy:7,fragile:false}};
const RAW=[
{id:"first-lock",chapter:0,title:"初次校平",brief:"一艘邮船完成西向东过闸。",levels:[0,2],initial:0,capacity:2,trips:[["W","eco",[["A",1,"mail"]]]]},
{id:"return-post",chapter:0,title:"回程邮路",brief:"利用返程减少空舱升降。",levels:[0,2],initial:0,capacity:2,trips:[["W","normal",[["A",1,"mail"]]],["E","eco",[["B",1,"mail"]]]]},
{id:"shared-chamber",chapter:0,title:"合舱冷链",brief:"两艘小船共享有限闸室。",levels:[1,3],initial:1,capacity:2,trips:[["W","normal",[["A",1,"food"],["B",1,"mail"]]],["E","eco",[["C",1,"food"]]]]},
{id:"glass-rule",chapter:1,title:"玻璃禁急",brief:"易碎货在舱时不能使用急泵。",levels:[0,3],initial:0,capacity:3,trips:[["W","normal",[["A",2,"glass"]]],["E","fast",[["B",1,"steel"]]]]},
{id:"heavy-pair",chapter:1,title:"重载拼舱",brief:"工程船与邮船恰好装满。",levels:[0,2],initial:2,capacity:4,trips:[["E","eco",[["A",2,"steel"],["B",1,"mail"]]],["W","normal",[["C",3,"timber"],["D",1,"food"]]]]},
{id:"empty-return",chapter:1,title:"空舱回落",brief:"连续东行迫使一次空舱回程。",levels:[0,3],initial:0,capacity:3,trips:[["W","fast",[["A",1,"rescue"],["B",1,"mail"]]],["W","eco",[["C",2,"glass"]]],["E","fast",[["D",1,"steel"]]]]},
{id:"storm-mail",chapter:2,title:"风暴邮线",brief:"优先件需要以急泵抢回时间。",levels:[1,3],initial:1,capacity:3,trips:[["W","fast",[["A",1,"rescue"],["B",2,"steel"]]],["E","normal",[["C",1,"glass"],["D",1,"mail"]]],["W","eco",[["E",1,"food"]]]]},
{id:"cross-current",chapter:2,title:"逆潮交班",brief:"三次满舱往返考验批次顺序。",levels:[0,2],initial:2,capacity:4,trips:[["E","normal",[["A",2,"timber"],["B",2,"food"]]],["W","fast",[["C",1,"rescue"],["D",2,"steel"],["E",1,"mail"]]],["E","eco",[["F",2,"glass"],["G",1,"mail"]]]]},
{id:"fragile-convoy",chapter:2,title:"易碎船队",brief:"两批玻璃货限制泵站选择。",levels:[0,3],initial:0,capacity:4,trips:[["W","normal",[["A",2,"glass"],["B",1,"mail"]]],["E","eco",[["C",2,"glass"],["D",2,"food"]]],["W","fast",[["E",1,"rescue"],["F",2,"steel"]]]]},
{id:"four-watches",chapter:3,title:"四更合流",brief:"四次往返混合速度与能耗目标。",levels:[1,3],initial:3,capacity:4,trips:[["E","eco",[["A",2,"timber"],["B",1,"mail"]]],["W","fast",[["C",1,"rescue"],["D",2,"steel"]]],["E","normal",[["E",1,"glass"],["F",1,"food"]]],["W","eco",[["G",2,"glass"],["H",1,"mail"]]]]},
{id:"tide-ledger",chapter:3,title:"潮账压缩",brief:"连续同向批次与返程货交织。",levels:[0,3],initial:3,capacity:5,trips:[["E","fast",[["A",2,"steel"],["B",1,"rescue"]]],["W","normal",[["C",2,"glass"],["D",2,"food"]]],["W","eco",[["E",3,"timber"],["F",1,"mail"]]],["E","fast",[["G",2,"steel"],["H",1,"rescue"]]]]},
{id:"harbor-finale",chapter:3,title:"港门终班",brief:"五批九船完成总闸联合调度。",levels:[0,3],initial:0,capacity:5,trips:[["W","fast",[["A",1,"rescue"],["B",2,"steel"],["C",1,"mail"]]],["E","normal",[["D",2,"glass"],["E",2,"food"]]],["W","eco",[["F",3,"timber"],["G",1,"mail"]]],["E","fast",[["H",2,"steel"]]],["W","normal",[["I",2,"glass"],["J",1,"food"]]]]}
];
const $=id=>document.getElementById(id),clone=value=>JSON.parse(JSON.stringify(value)),opposite=side=>side==="W"?"E":"W",hash=text=>{let value=2166136261;for(let i=0;i<text.length;i++){value^=text.charCodeAt(i);value=Math.imul(value,16777619)}return(value>>>0).toString(36)},to64=text=>btoa(unescape(encodeURIComponent(text))),from64=text=>decodeURIComponent(escape(atob(text)));
function makeSpec(raw){const boats=[];raw.trips.forEach((trip,tripIndex)=>trip[2].forEach(([id,size,kind])=>boats.push({id,size,kind,fragile:kind==="glass",origin:trip[0],dest:opposite(trip[0]),trip:tripIndex,deadline:999})));return{...raw,boats}}
const CONTRACTS=RAW.map(makeSpec);
function freshProfile(){return{contract:0,stars:Array(12).fill(0),bestTime:Array(12).fill(null),bestEnergy:Array(12).fill(null),clears:Array(12).fill(0)}}
let profile=freshProfile(),state,history=[];
function freshState(index=profile.contract){const spec=CONTRACTS[index];return{index,level:spec.initial,gate:null,time:0,energy:0,hints:0,boats:Object.fromEntries(spec.boats.map(boat=>[boat.id,"origin"])),delivered:{},log:[],result:null}}
function loadSize(spec,s=state){return spec.boats.filter(boat=>s.boats[boat.id]==="chamber").reduce((sum,boat)=>sum+boat.size,0)}
function sideLevel(spec,side){return spec.levels[side==="W"?0:1]}
function boatById(spec,id){return spec.boats.find(boat=>boat.id===id)}
function canPerform(spec,s,action){
if(!action||s.result?.won)return false;
if(action.type==="gate"){if(!["W","E"].includes(action.side))return false;if(s.gate===action.side)return true;return s.gate===null&&s.level===sideLevel(spec,action.side)}
if(action.type==="pump"){const mode=MODES[action.mode],next=s.level+action.dir;if(!mode||![-1,1].includes(action.dir)||s.gate!==null||next<0||next>3)return false;if(!mode.fragile&&spec.boats.some(boat=>boat.fragile&&s.boats[boat.id]==="chamber"))return false;return true}
if(action.type==="load"){const boat=boatById(spec,action.id);return Boolean(boat&&s.boats[boat.id]==="origin"&&s.gate===boat.origin&&s.level===sideLevel(spec,boat.origin)&&loadSize(spec,s)+boat.size<=spec.capacity)}
if(action.type==="unload"){const boat=boatById(spec,action.id);return Boolean(boat&&s.boats[boat.id]==="chamber"&&s.gate===boat.dest&&s.level===sideLevel(spec,boat.dest))}
if(action.type==="wait")return s.gate===null;
return false;
}
function perform(spec,s,action){if(!canPerform(spec,s,action))return false;if(action.type==="gate"){const closing=s.gate===action.side;s.gate=closing?null:action.side;s.time++;s.log.push(`${closing?"关闭":"开启"}${SIDE_NAME[action.side]}闸门`)}else if(action.type==="pump"){const mode=MODES[action.mode],cargo=loadSize(spec,s);s.level+=action.dir;s.time+=mode.time;s.energy+=mode.energy+cargo*(action.mode==="fast"?2:1);s.log.push(`${mode.label}${action.dir>0?"升":"降"}至 L${s.level}`)}else if(action.type==="load"){const boat=boatById(spec,action.id);s.boats[boat.id]="chamber";s.time++;s.log.push(`${boat.id} 号船由${SIDE_NAME[boat.origin]}进舱`)}else if(action.type==="unload"){const boat=boatById(spec,action.id);s.boats[boat.id]="done";s.time++;s.delivered[boat.id]=s.time;s.log.push(`${boat.id} 号船抵达${SIDE_NAME[boat.dest]}`)}else{s.time++;s.log.push("等待 1 刻")};return true}
function addLevelActions(actions,from,to,mode){let level=from;while(level!==to){const dir=Math.sign(to-level);actions.push({type:"pump",dir,mode});level+=dir}return level}
function referenceActions(spec){const actions=[];let level=spec.initial;for(const trip of spec.trips){const origin=trip[0],dest=opposite(origin),mode=trip[1],originLevel=sideLevel(spec,origin),destLevel=sideLevel(spec,dest);level=addLevelActions(actions,level,originLevel,"eco");actions.push({type:"gate",side:origin});trip[2].forEach(item=>actions.push({type:"load",id:item[0]}));actions.push({type:"gate",side:origin});level=addLevelActions(actions,level,destLevel,mode);actions.push({type:"gate",side:dest});trip[2].forEach(item=>actions.push({type:"unload",id:item[0]}));actions.push({type:"gate",side:dest})}return actions}
function simulate(spec,actions=referenceActions(spec)){const s=freshState(CONTRACTS.indexOf(spec));let legal=true,maxLoad=0,fastFragileRejected=false;for(const action of actions){if(!canPerform(spec,s,action)){legal=false;break}perform(spec,s,action);maxLoad=Math.max(maxLoad,loadSize(spec,s))}const allDone=spec.boats.every(boat=>s.boats[boat.id]==="done");return{state:s,legal,allDone,maxLoad,actions:actions.length,late:spec.boats.filter(boat=>s.delivered[boat.id]!==undefined&&s.delivered[boat.id]>boat.deadline).length,fastFragileRejected}}
CONTRACTS.forEach(spec=>{spec.reference=referenceActions(spec);let run=simulate(spec,spec.reference);spec.boats.forEach(boat=>boat.deadline=run.state.delivered[boat.id]+3);run=simulate(spec,spec.reference);spec.goalTime=run.state.time;spec.goalEnergy=run.state.energy;spec.referenceResult=run;spec.chapterName=CHAPTERS[spec.chapter]});
function evaluate(spec,s){const allDone=spec.boats.every(boat=>s.boats[boat.id]==="done"),late=spec.boats.filter(boat=>s.delivered[boat.id]!==undefined&&s.delivered[boat.id]>boat.deadline).length,closed=s.gate===null,won=allDone&&late===0&&closed;let stars=won?1:0;if(won&&(s.time<=spec.goalTime+2||s.energy<=spec.goalEnergy+2))stars=2;if(won&&s.time<=spec.goalTime&&s.energy<=spec.goalEnergy&&s.hints===0)stars=3;return{won,stars,late,closed,allDone,time:s.time,energy:s.energy}}
function stateKey(s){return JSON.stringify({level:s.level,gate:s.gate,time:s.time,energy:s.energy,boats:s.boats})}
function nextReference(){const spec=CONTRACTS[state.index],probe=freshState(state.index);if(stateKey(probe)===stateKey(state))return spec.reference[0];for(let i=0;i<spec.reference.length;i++){perform(spec,probe,spec.reference[i]);if(stateKey(probe)===stateKey(state))return spec.reference[i+1]||null}return undefined}
function describeAction(action){if(!action)return"本班参考调度已经完成,请交班验收。";if(action.type==="gate")return`${state.gate===action.side?"关闭":"开启"}${SIDE_NAME[action.side]}闸门`;if(action.type==="pump")return`使用${MODES[action.mode].label}${action.dir>0?"提升":"降低"}一档水位`;if(action.type==="load")return`让 ${action.id} 号船进入闸室`;if(action.type==="unload")return`让 ${action.id} 号船驶出闸室`;return"等待一刻"}
function snapshot(){return clone(state)}
function apply(action,record=true){const spec=CONTRACTS[state.index];if(!canPerform(spec,state,action)){setStatus(explainInvalid(spec,action),"bad");return false}if(record){history.push(snapshot());if(history.length>80)history.shift()}perform(spec,state,action);state.result=null;refresh();return true}
function explainInvalid(spec,action){if(action.type==="gate")return`无法开闸:闸室需校平到 ${SIDE_NAME[action.side]}的 L${sideLevel(spec,action.side)},且另一侧闸门必须关闭。`;if(action.type==="pump")return action.mode==="fast"&&spec.boats.some(boat=>boat.fragile&&state.boats[boat.id]==="chamber")?"急泵被拒绝:闸室内有易碎玻璃货。":"无法泵水:先关闭闸门,并确认水位未到边界。";if(action.type==="load")return"无法进舱:检查闸门、水位和剩余舱容。";if(action.type==="unload")return"无法出舱:必须在目的岸水位开启对应闸门。";return"当前动作不符合船闸规则。"}
function begin(index){profile.contract=Math.max(0,Math.min(CONTRACTS.length-1,index));state=freshState(profile.contract);history.length=0;refresh();setStatus("选择闸门开始调度。")}
function undo(){const saved=history.pop();if(!saved){setStatus("没有可撤回的调度动作。");return}state=saved;refresh();setStatus("已撤回上一步。")}
function reset(){state=freshState(state.index);history.length=0;refresh();setStatus("本班调度已重置。")}
function hint(){const action=nextReference();if(action===undefined){setStatus("当前路线已偏离参考批次;先撤回或重置,再请求调度提示。","bad");return}if(!action){setStatus(describeAction(action),"good");return}const words=describeAction(action);if(apply(action)){state.hints++;setStatus(`提示已执行:${words}。`)}}
function verify(){const spec=CONTRACTS[state.index],result=evaluate(spec,state);state.result=result;profile.clears[state.index]++;if(result.won){profile.stars[state.index]=Math.max(profile.stars[state.index],result.stars);if(profile.bestTime[state.index]===null||result.time<profile.bestTime[state.index])profile.bestTime[state.index]=result.time;if(profile.bestEnergy[state.index]===null||result.energy<profile.bestEnergy[state.index])profile.bestEnergy[state.index]=result.energy;saveProfile()}refresh();showResult(spec,result)}
function saveProfile(){localStorage.setItem("lockmaster-shift-profile",JSON.stringify(profile))}
function loadProfile(){try{const raw=JSON.parse(localStorage.getItem("lockmaster-shift-profile")||"null");if(raw?.stars?.length===CONTRACTS.length)profile={...freshProfile(),...raw}}catch{profile=freshProfile()}}
function setStatus(text,tone=""){const node=$("statusText");node.textContent=text;node.className=`status ${tone}`}
function boatButton(spec,boat){const button=document.createElement("button"),place=state.boats[boat.id],ready=place==="origin"?state.gate===boat.origin:place==="chamber"?state.gate===boat.dest:false;button.className=`boat${boat.fragile?" fragile":""}${ready?" ready":""}`;button.dataset.boat=boat.id;button.innerHTML=`${boat.id} · ${KIND[boat.kind][1]}${boat.size}<small>${SIDE_NAME[boat.origin]}→${SIDE_NAME[boat.dest]} · 限 ${boat.deadline}</small>`;return button}
function renderBoats(){const spec=CONTRACTS[state.index],hosts={W:$("westBoats"),E:$("eastBoats"),chamber:$("chamberBoats")};Object.values(hosts).forEach(host=>host.replaceChildren());spec.boats.forEach(boat=>{const place=state.boats[boat.id];if(place==="done")return;const host=place==="chamber"?hosts.chamber:hosts[boat.origin];host.append(boatButton(spec,boat))});Object.values(hosts).forEach(host=>{if(!host.children.length){const empty=document.createElement("span");empty.className="empty";empty.textContent=host===hosts.chamber?"闸室空载":"本岸无待闸船";host.append(empty)}});$("capacityText").textContent=`${loadSize(spec)} / ${spec.capacity}`}
function renderShifts(){const host=$("shiftList");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="shift-grid";CONTRACTS.filter(item=>item.chapter===chapterIndex).forEach(spec=>{const index=CONTRACTS.indexOf(spec),button=document.createElement("button");button.className=`shift${index===state.index?" active":""}${profile.stars[index]>=3?" done":""}`;button.dataset.index=index;button.innerHTML=`<strong>${String(index+1).padStart(2,"0")} · ${spec.title}</strong><small>${profile.stars[index]?"★".repeat(profile.stars[index])+" · ":""}${spec.boats.length} 船 / ${spec.trips.length} 批</small>`;grid.append(button)});host.append(grid)});$("progressText").textContent=`${profile.stars.filter(Boolean).length} / ${CONTRACTS.length}`}
function draw(){const canvas=$("lockCanvas"),ctx=canvas.getContext("2d"),spec=CONTRACTS[state.index],w=canvas.width,h=canvas.height,base=h-40,unit=54,waterY=base-state.level*unit,westY=base-spec.levels[0]*unit,eastY=base-spec.levels[1]*unit;ctx.clearRect(0,0,w,h);ctx.fillStyle="#153a43";ctx.fillRect(0,0,w,h);ctx.fillStyle="#d8d0b6";ctx.fillRect(0,base+2,w,h-base);ctx.fillStyle="#347f9a";ctx.fillRect(0,westY,w*.27,base-westY);ctx.fillRect(w*.73,eastY,w*.27,base-eastY);ctx.fillStyle="#2d6e86";ctx.fillRect(w*.28,waterY,w*.44,base-waterY);ctx.fillStyle="rgba(255,255,255,.16)";for(let x=0;x<w;x+=46){ctx.fillRect(x,westY+7,28,2);ctx.fillRect(x,eastY+13,28,2);ctx.fillRect(x,waterY+5,28,2)}const gates=[{x:w*.275,side:"W"},{x:w*.725,side:"E"}];gates.forEach(gate=>{const open=state.gate===gate.side;ctx.fillStyle=open?"#e5bd57":"#6d4734";ctx.fillRect(gate.x-7,open?base-18:34,14,open?20:base-32);ctx.fillStyle="#f0d174";ctx.fillRect(gate.x-10,30,20,8)});ctx.fillStyle="#dfeceb";ctx.font="bold 13px system-ui";ctx.textAlign="center";ctx.fillText(`西岸 L${spec.levels[0]}`,w*.13,25);ctx.fillText(`闸室 L${state.level}`,w*.5,25);ctx.fillText(`东岸 L${spec.levels[1]}`,w*.87,25);const chamber=spec.boats.filter(boat=>state.boats[boat.id]==="chamber");chamber.forEach((boat,index)=>drawBoat(ctx,w*.38+index*67,Math.max(58,waterY-22),boat));spec.boats.filter(boat=>state.boats[boat.id]==="origin"&&boat.origin==="W").slice(0,4).forEach((boat,index)=>drawBoat(ctx,38+index*55,Math.max(58,westY-20),boat,.78));spec.boats.filter(boat=>state.boats[boat.id]==="origin"&&boat.origin==="E").slice(0,4).forEach((boat,index)=>drawBoat(ctx,w-82-index*55,Math.max(58,eastY-20),boat,.78))}
function drawBoat(ctx,x,y,boat,scale=1){ctx.save();ctx.translate(x,y);ctx.scale(scale,scale);ctx.fillStyle=boat.fragile?"#d1a249":boat.kind==="rescue"?"#d35c55":"#e8e2cf";ctx.beginPath();ctx.moveTo(-25,0);ctx.lineTo(27,0);ctx.lineTo(18,16);ctx.lineTo(-18,16);ctx.closePath();ctx.fill();ctx.fillStyle="#17333a";ctx.font="bold 12px system-ui";ctx.textAlign="center";ctx.fillText(boat.id,0,12);ctx.restore()}
function refresh(){const spec=CONTRACTS[state.index],result=evaluate(spec,state);$("shiftTitle").textContent=`${String(state.index+1).padStart(2,"0")} · ${spec.title}`;$("shiftBrief").textContent=spec.brief;$("timeMetric").textContent=state.time;$("energyMetric").textContent=state.energy;$("levelMetric").textContent=`L${state.level}`;$("westLevelText").textContent=`L${spec.levels[0]}`;$("eastLevelText").textContent=`L${spec.levels[1]}`;$("goalText").innerHTML=`三星 ≤ ${spec.goalTime} 刻 / ${spec.goalEnergy} 能耗<br>${spec.boats.length} 船 · 舱容 ${spec.capacity}`;$("westGate").textContent=state.gate==="W"?"关闭西闸":"开启西闸";$("eastGate").textContent=state.gate==="E"?"关闭东闸":"开启东闸";$("westGate").disabled=state.gate!==null&&state.gate!=="W";$("eastGate").disabled=state.gate!==null&&state.gate!=="E";$("pumpDown").disabled=state.gate!==null||state.level===0;$("pumpUp").disabled=state.gate!==null||state.level===3;$("actionLog").innerHTML=state.log.length?state.log.slice(-7).reverse().map((entry,index)=>`<div>${state.log.length-index}. ${entry}</div>`).join(""):"值班记录尚为空。";renderBoats();renderShifts();draw();if(result.won)setStatus(`全部船只已按时抵达,可交班验收 ${result.stars} 星。`,"good")}
function showResult(spec,result){$("dialogTitle").textContent=result.won?`${spec.title} · 交班通过`:`${spec.title} · 尚未交班`;$("dialogSummary").textContent=result.won?`获得 ${result.stars} 星;用时 ${result.time} 刻,泵站能耗 ${result.energy}。`:`当前完成 ${spec.boats.filter(boat=>state.boats[boat.id]==="done").length}/${spec.boats.length} 船,用时 ${result.time} 刻,能耗 ${result.energy}。`;$("dialogDetail").textContent=result.won?"记录已写入值班档案。尝试重新分批或切换泵水模式,可以继续压缩时刻与能耗。":result.late?`已有 ${result.late} 艘船超过交付时限,请重置后调整优先批次。`:result.allDone&&!result.closed?"全部船只已抵达,但必须关闭闸门后才能交班。":"仍有船只未抵达目的岸;检查闸室、水位和两岸待闸队列。";$("resultDialog").showModal()}
function encodeArchive(p=profile){const data={contract:p.contract,stars:p.stars,bestTime:p.bestTime,bestEnergy:p.bestEnergy,clears:p.clears},body=JSON.stringify(data);return`${ARCHIVE}.${to64(JSON.stringify({...data,check:hash(body)}))}`}
function decodeArchive(code){if(typeof code!=="string"||!code.startsWith(`${ARCHIVE}.`))throw Error("档案前缀错误");const payload=JSON.parse(from64(code.slice(ARCHIVE.length+1))),{check,...data}=payload;if(check!==hash(JSON.stringify(data)))throw Error("档案校验失败");if(!Array.isArray(data.stars)||data.stars.length!==CONTRACTS.length)throw Error("档案内容错误");return data}
function exportArchive(){$("archiveCode").value=encodeArchive();setStatus("档案已生成,可复制到另一台设备。","good")}
function importArchive(){try{profile={...freshProfile(),...decodeArchive($("archiveCode").value.trim())};saveProfile();begin(profile.contract);setStatus("档案导入成功。","good")}catch(error){setStatus(`导入失败:${error.message}`,"bad")}}
$("shiftList").addEventListener("click",event=>{const button=event.target.closest("[data-index]");if(button)begin(Number(button.dataset.index))});["westBoats","eastBoats","chamberBoats"].forEach(id=>$(id).addEventListener("click",event=>{const button=event.target.closest("[data-boat]");if(!button)return;const spec=CONTRACTS[state.index],boat=boatById(spec,button.dataset.boat),type=state.boats[boat.id]==="origin"?"load":"unload";apply({type,id:boat.id})}));$("westGate").addEventListener("click",()=>apply({type:"gate",side:"W"}));$("eastGate").addEventListener("click",()=>apply({type:"gate",side:"E"}));$("pumpDown").addEventListener("click",()=>apply({type:"pump",dir:-1,mode:$("pumpMode").value}));$("pumpUp").addEventListener("click",()=>apply({type:"pump",dir:1,mode:$("pumpMode").value}));$("waitButton").addEventListener("click",()=>apply({type:"wait"}));$("verifyButton").addEventListener("click",verify);$("hintButton").addEventListener("click",hint);$("undoButton").addEventListener("click",undo);$("resetButton").addEventListener("click",reset);$("exportButton").addEventListener("click",exportArchive);$("importButton").addEventListener("click",importArchive);$("closeDialog").addEventListener("click",()=>$("resultDialog").close());
loadProfile();state=freshState(profile.contract);window.__lockmasterTest={contracts:CONTRACTS,chapters:CHAPTERS,modes:MODES,getState:()=>clone(state),freshState,begin,canPerform:(s,a,index=s.index)=>canPerform(CONTRACTS[index],s,a),perform:(s,a,index=s.index)=>perform(CONTRACTS[index],s,a),apply,evaluate:(s=state,index=s.index)=>evaluate(CONTRACTS[index],s),referenceActions:index=>clone(CONTRACTS[index].reference),runReference:index=>simulate(CONTRACTS[index],CONTRACTS[index].reference),encodeArchive,decodeArchive,freshProfile,validateContent:()=>{const references=CONTRACTS.map((spec,index)=>{const run=simulate(spec,spec.reference),result=evaluate(spec,run.state);return{id:spec.id,legal:run.legal,won:result.won,stars:result.stars,boats:spec.boats.length,trips:spec.trips.length,actions:spec.reference.length,time:run.state.time,energy:run.state.energy,maxLoad:run.maxLoad,capacity:spec.capacity,levels:spec.levels.join("-"),modes:[...new Set(spec.trips.map(trip=>trip[1]))].join("/")}});return{contracts:CONTRACTS.length,chapters:CHAPTERS.length,boats:CONTRACTS.reduce((sum,spec)=>sum+spec.boats.length,0),trips:CONTRACTS.reduce((sum,spec)=>sum+spec.trips.length,0),fragile:CONTRACTS.reduce((sum,spec)=>sum+spec.boats.filter(boat=>boat.fragile).length,0),kinds:new Set(CONTRACTS.flatMap(spec=>spec.boats.map(boat=>boat.kind))).size,referenceWins:references.filter(item=>item.legal&&item.won).length,referenceThreeStars:references.filter(item=>item.stars===3).length,uniqueRules:new Set(references.map(item=>`${item.levels}/${item.capacity}/${item.modes}/${item.trips}`)).size,references}}};refresh();
})();
</script>
</body>
</html>