'use strict'; const $ = id => document.getElementById(id); const clone = value => JSON.parse(JSON.stringify(value)); const icons = () => window.lucide.createIcons(); const state = { mode: 'mainline', level: null, revision: '', baseline: '', definitions: [], selected: null, material: null, kind: 'characters', view: 'source', history: [], future: [], result: null, sequence: 0, zoom: 1, pan: { x: 0, y: 0 }, drag: null, hover: null, busy: false, draft: null }; const images = new Map(); const canvas = $('board'), ctx = canvas.getContext('2d'); let transform = null, validateTimer; const layoutText = level => JSON.stringify([level.width, level.height, level.characters, level.aoes]); const dirty = () => state.level && layoutText(state.level) !== state.baseline; const selectedEntry = () => state.selected && state.level?.[state.selected.collection]?.[state.selected.index]; const definitionFor = entry => state.definitions.find(item => item.id === entry?.[0]); const draftKey = () => 'level-editor:' + state.project + ':source:' + state.sourceLevel; function message(text, error = false) { $('message').textContent = text; $('message').classList.toggle('error', error); } function setBusy(value) { state.busy = value; document.body.classList.toggle('busy', value); $('save').disabled = value; $('open').disabled = value; } async function api(url, body) { if (state.mode === 'ghost-king') { url = url.replace('/api/levels/', '/api/ghost-levels/'); if (url === '/api/validate') url = '/api/ghost-validate'; } const adaptBootstrap = data => url === '/api/bootstrap' ? { ...data, mainlineCount: data.levelCount, levelCount: state.mode === 'ghost-king' ? data.ghostCount : data.levelCount } : data; if (window.offlineEditor) return adaptBootstrap(await window.offlineEditor.api(url, body)); const response = await fetch(url, body === undefined ? {} : { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Editor-Token': state.token }, body: JSON.stringify(body) }); const data = await response.json(); if (!response.ok) throw new Error(data.error || '请求失败'); return adaptBootstrap(data); } function guarded(action) { return (...args) => Promise.resolve().then(() => action(...args)).catch(error => message(error.message, true)); } $('level-mode').onchange = guarded(async () => { const previous = state.mode, next = $('level-mode').value; if (state.busy || ((dirty() || pendingExtra()) && !confirm('当前关卡有未保存修改,是否切换模式?'))) { $('level-mode').value = previous; return; } state.mode = next; state.sequence++; state.level = null; state.baseline = ''; state.selected = null; state.levelCount = next === 'ghost-king' ? state.ghostCount : state.mainlineCount; $('level-total').textContent = '/ ' + state.levelCount; $('level-number').max = state.levelCount; $('mainline-manage').disabled = next === 'ghost-king'; await openLevel(1); }); function imageFor(url) { if (!url) return null; if (!images.has(url)) { const image = new Image(); image.onload = draw; image.onerror = () => { image.failed = true; draw(); }; image.src = url; images.set(url, image); } return images.get(url); } function makeThumbnail(definition, parent) { parent.classList.toggle('has-overlay', Boolean(definition?.overlay)); if (definition?.image) { const image = document.createElement('img'); image.src = definition.image; image.alt = definition.name; parent.append(image); if (definition.overlay) { const overlay = document.createElement('img'); overlay.src = definition.overlay; overlay.alt = ''; overlay.className = 'entity-overlay'; parent.append(overlay); } } else { const icon = document.createElement('i'); icon.dataset.lucide = 'fence'; icon.className = 'mechanism-symbol'; parent.append(icon); } } function renderLibrary() { const search = $('search').value.trim().toLowerCase(); const definitions = state.definitions.filter(item => item.collection === state.kind && (item.name.toLowerCase().includes(search) || String(item.id).includes(search))); $('material-count').textContent = definitions.length + ' 项'; $('materials').replaceChildren(); definitions.forEach(definition => { const button = document.createElement('button'); button.className = 'material'; button.title = definition.name; button.classList.toggle('active', state.material?.id === definition.id); const thumbnail = document.createElement('div'); thumbnail.className = 'thumbnail'; makeThumbnail(definition, thumbnail); const name = document.createElement('strong'); name.textContent = definition.name; const id = document.createElement('small'); id.textContent = definition.id; button.append(thumbnail, name, id); button.onclick = () => { if (state.busy) return; state.material = definition; state.selected = null; state.view = 'source'; state.hover = null; renderLibrary(); render(); message('已选择:' + definition.name); }; $('materials').append(button); }); icons(); } function renderInspector() { const entry = selectedEntry(), definition = definitionFor(entry); $('properties').hidden = !entry; $('selection-empty').hidden = Boolean(entry); document.querySelectorAll('#properties input,#properties select,#properties textarea,#properties button,.board-settings input').forEach(input => { input.disabled = state.view !== 'source'; }); $('selection-kind').textContent = entry ? (state.selected.collection === 'characters' ? '军械' : '机关') : ''; if (!entry || !definition) return; $('selected-name').textContent = definition.name; $('selected-id').textContent = '类型 ' + entry[0] + ' · 序号 ' + (state.selected.index + 1); $('selected-image').replaceChildren(); makeThumbnail(definition, $('selected-image')); const options = state.definitions.filter(item => item.collection === state.selected.collection); $('object-type').replaceChildren(...options.map(item => { const option = document.createElement('option'); option.value = item.id; option.textContent = item.name; return option; })); $('object-type').value = entry[0]; $('col').value = entry[1]; $('row').value = entry[2]; $('orientation').value = entry[3]; const footprint = definition.footprintsByOrientation[entry[3]]; $('footprint').textContent = footprint ? footprint.width + ' × ' + footprint.height : '无效'; const behaviors = { standard: '普通军械', collisionBomb: '碰撞炸弹', automaticExit: '自动离场', countdownBomb: '倒计时炸弹', movingHazard: '移动障碍', sealedUntilCollision: '碰撞唤醒', charmLeader: '牵引', bounceBack: '碰撞折返', fenceBreaker: '破栏', limitedStep: '步数限制', burrowingBlocker: '出入地面', teamLeader: '编队领队', teamMember: '编队成员', fence: '栏杆', cage: '封印锁' }; $('behavior').textContent = behaviors[definition.boardBehavior] || definition.boardBehavior; $('sprite-facing').textContent = ['fence', 'cage'].includes(definition.boardBehavior) ? '随横竖布局调整' : definition.visual?.spriteRotationMode === 'directional' ? '随方向旋转' : '固定直立'; $('extra').value = JSON.stringify(entry[4] || {}, null, 2); renderExtraFields(entry, definition); icons(); } function render() { if (!state.level) return; const level = state.level; $('title').textContent = '第 ' + level.displayLevel + ' 关'; $('subtitle').textContent = level.width + ' × ' + level.height + ' · ' + level.sourceId; $('level-number').value = level.displayLevel; $('dirty').textContent = dirty() ? '未保存' : '已保存'; $('dirty').classList.toggle('modified', dirty()); $('counts').textContent = level.characters.length + ' 军械 / ' + level.aoes.length + ' 机关'; $('source-id').textContent = level.sourceId; $('scene').textContent = state.result?.scene || '-'; $('columns').value = level.width; $('rows').value = level.height; $('undo').disabled = !state.history.length; $('redo').disabled = !state.future.length; for (const id of ['rotate', 'duplicate', 'delete']) $(id).disabled = !selectedEntry() || state.view !== 'source'; $('select-tool').classList.toggle('active', !state.material); document.querySelectorAll('[data-view]').forEach(button => button.classList.toggle('active', button.dataset.view === state.view)); $('view-state').textContent = state.view === 'source' ? (state.material ? '放置 · ' + state.material.name : '源布局') : '局内预览 · 只读'; $('zoom-label').textContent = Math.round(state.zoom * 100) + '%'; $('draft-actions').hidden = !state.draft; renderInspector(); draw(); } function draftSave() { try { if (dirty()) localStorage.setItem(draftKey(), JSON.stringify({ level: state.level, revision: state.revision, updated: Date.now() })); else localStorage.removeItem(draftKey()); } catch { message('本地草稿存储失败,请及时保存或导出', true); } } function changed(before) { if (JSON.stringify(before) === JSON.stringify(state.level)) return; state.history.push(before); if (state.history.length > 80) state.history.shift(); state.future.length = 0; state.sequence++; state.result = null; draftSave(); render(); scheduleValidation(); } function mutate(action) { if (!state.level || state.busy || state.view !== 'source') return; const before = clone(state.level); if (pendingExtra()) { const value = readExtraInput(), problems = window.LevelExtraFields.validate(value); if (problems.length) throw new Error(problems[0]); selectedEntry()[4] = value; } action(); changed(before); } function localIssues(level) { const occupied = new Set(), issues = []; for (const collection of ['characters', 'aoes']) for (const [index, entry] of level[collection].entries()) { const definition = definitionFor(entry), footprint = definition?.footprintsByOrientation[entry[3]]; if (!footprint || !entry.slice(0, 4).every(Number.isSafeInteger)) { issues.push('对象数据无效'); continue; } for (const [dx, dy] of footprint.cells) { const col = entry[1] + dx, row = entry[2] + dy, key = col + ',' + row; if (col < 0 || row < 0 || col >= level.width || row >= level.height) issues.push('对象超出棋盘'); if (collection === 'characters') { if (occupied.has(key)) issues.push('军械占格重叠'); occupied.add(key); } } } return issues; } function updateSelected(index, value) { const entry = selectedEntry(); if (!entry) return; if (!Number.isSafeInteger(value)) { renderInspector(); throw new Error('请输入整数'); } mutate(() => { entry[index] = value; }); } function applyExtra() { const entry = selectedEntry(); if (!entry) return; const value = readExtraInput(); const problems = window.LevelExtraFields.validate(value); if (problems.length) throw new Error(problems[0]); if (JSON.stringify(value) === JSON.stringify(entry[4] || {})) { if ($('extra-path')) $('extra-path').dataset.dirty = 'false'; return; } mutate(() => { entry[4] = value; }); } function pendingExtra() { const entry = selectedEntry(); return entry && ($('extra').value !== JSON.stringify(entry[4] || {}, null, 2) || $('extra-path')?.dataset.dirty === 'true'); } async function openLevel(number) { if (state.busy) return; if (!Number.isInteger(number) || number < 1 || number > state.levelCount) throw new Error('关卡编号超出范围'); if ((dirty() || pendingExtra()) && !confirm('当前关卡有未保存修改,是否切换?')) { render(); return; } state.sequence++; clearTimeout(validateTimer); setBusy(true); try { const result = await api('/api/levels/' + number); state.level = result.level; state.sourceLevel = result.sourceLevel; state.revision = result.revision; state.baseline = layoutText(result.level); state.result = result; state.history = []; state.future = []; state.selected = null; state.material = null; state.drag = null; state.view = 'source'; state.zoom = 1; state.pan = { x: 0, y: 0 }; state.draft = null; try { const draft = JSON.parse(localStorage.getItem(draftKey())); if (draft?.level && layoutText(draft.level) !== state.baseline) { draft.level.displayLevel = number; state.draft = draft; } } catch { message('本地草稿读取失败', true); } renderLibrary(); render(); showValidation(result); message('已打开第 ' + number + ' 关'); } finally { setBusy(false); } } function showValidation(result) { $('validation-status').textContent = result.issues.length ? result.issues.length + ' 个问题' : '通过'; $('validation-status').className = result.issues.length ? 'error' : 'ok'; $('issues').replaceChildren(); if (!result.issues.length) { $('issues').textContent = '源占格与游戏布局适配通过'; return; } result.issues.forEach(issue => { const button = document.createElement('button'); button.className = 'issue'; button.textContent = issue.message; button.onclick = () => { if (issue.collection && Number.isInteger(issue.entryIndex)) { state.selected = { collection: issue.collection, index: issue.entryIndex }; state.material = null; state.view = 'source'; render(); } }; $('issues').append(button); }); } async function validate() { if (!state.level) return; const sequence = ++state.sequence, level = clone(state.level); $('validation-status').textContent = '正在校验'; const result = await api('/api/validate', { level }); if (sequence !== state.sequence) return; state.result = result; showValidation(result); $('scene').textContent = result.scene || '-'; refreshExtraEffective(); draw(); return result; } function scheduleValidation() { clearTimeout(validateTimer); $('validation-status').textContent = '待校验'; validateTimer = setTimeout(guarded(validate), 300); } async function save() { if (!state.level || state.busy) return; if (pendingExtra()) applyExtra(); clearTimeout(validateTimer); state.sequence++; setBusy(true); try { const result = await api('/api/levels/' + state.level.displayLevel, { level: state.level, revision: state.revision }); state.revision = result.revision; state.baseline = layoutText(state.level); state.result = result; state.draft = null; draftSave(); render(); showValidation(result); message('已保存;备份:' + result.backup); } finally { setBusy(false); } } function displayedEntities() { if (!state.level) return []; if (state.view === 'preview') { if (!state.result?.board) return []; return [...state.result.board.units.map((unit, index) => ({ collection: 'characters', index, entry: [unit.artifactId, unit.col, unit.row, unit.sourceOrientation, unit.sourceExtra] })), ...state.result.board.aoes.map((unit, index) => ({ collection: 'aoes', index, entry: [unit.mechanismId, unit.col, unit.row, unit.sourceOrientation] }))]; } return ['characters', 'aoes'].flatMap(collection => state.level[collection].map((entry, index) => ({ collection, index, entry }))); } function spriteAngle(definition, direction) { const footprint = definition.footprintsByOrientation[direction]; // 舞女图像保持直立,横竖占格仍由方向决定;机关的 Canvas 旋转正方向与 Cocos 相反。 if (definition.boardBehavior === 'movingHazard') return 0; if (definition.collection === 'aoes') return (definition.boardBehavior === 'cage' && footprint.height > footprint.width) || (definition.boardBehavior === 'fence' && [2, 4].includes(Number(direction))) ? -90 : 0; return definition.visual?.spriteRotationMode === 'directional' ? ({ 1: 180, 2: 90, 3: 0, 4: -90 }[direction] + Number(definition.visual?.spriteForwardOffsetDeg || 0)) : 0; } function drawEntity(entry, selected = false, ghost = false, invalid = false) { const definition = definitionFor(entry), footprint = definition?.footprintsByOrientation[entry[3]]; if (!footprint) return; const [id, col, row, direction] = entry; ctx.save(); if (ghost) ctx.globalAlpha = 0.65; const mechanism = definition.collection === 'aoes'; ctx.lineWidth = selected ? 0.045 : 0.018; for (const [dx, dy] of footprint.cells) { ctx.fillStyle = invalid ? '#fce0de' : selected ? '#cfebea' : mechanism ? '#f2e8d0' : '#e2ede6'; ctx.strokeStyle = invalid ? '#d5544b' : selected ? '#07858c' : mechanism ? '#c4a16c' : '#b8cfc0'; ctx.fillRect(col + dx + .035, row + dy + .035, .93, .93); ctx.strokeRect(col + dx + .035, row + dy + .035, .93, .93); } const lowered = definition.boardBehavior === 'burrowingBlocker' && window.LevelExtraFields.down(entry[4]); const stateImage = definition.stateImages?.underground || (definition.statePrefabIds?.underground ? '/assets/resources/Ynyk/Props/' + definition.statePrefabIds.underground + '.png' : null); const image = imageFor(lowered && stateImage ? stateImage : definition.image); if (image?.complete && image.naturalWidth && !image.failed) { ctx.save(); ctx.translate(col + footprint.width / 2, row + footprint.height / 2); if (lowered) ctx.globalAlpha *= 135 / 255; // 项目图片朝上,和占格配置的朝右基准不同;沿用局内展示层的朝向约定。 const angle = spriteAngle(definition, direction); ctx.rotate(angle * Math.PI / 180); const sideways = Math.abs(Math.sin(angle * Math.PI / 180)) > .5; const width = (sideways ? footprint.height : footprint.width) - .12; const height = (sideways ? footprint.width : footprint.height) - .12; const fit = Math.min(width / image.naturalWidth, height / image.naturalHeight); ctx.drawImage(image, -image.naturalWidth * fit / 2, -image.naturalHeight * fit / 2, image.naturalWidth * fit, image.naturalHeight * fit); ctx.restore(); } else { ctx.fillStyle = mechanism ? '#8a6b39' : '#456b5b'; ctx.font = '0.22px "Microsoft YaHei"'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(definition.name, col + footprint.width / 2, row + footprint.height / 2, footprint.width - .12); } const overlay = imageFor(definition.overlay); if (overlay?.complete && overlay.naturalWidth && !overlay.failed) { ctx.save(); ctx.translate(col + footprint.width / 2, row + footprint.height / 2); ctx.rotate(spriteAngle(definition, direction) * Math.PI / 180); // 按对象库 52 × 44 缩略图中标记的占比绘制,保持相对箭身的大小一致。 const angle = spriteAngle(definition, direction); const sideways = Math.abs(Math.sin(angle * Math.PI / 180)) > .5; const availableWidth = (sideways ? footprint.height : footprint.width) - .12; const availableHeight = (sideways ? footprint.width : footprint.height) - .12; const arrowHeight = image?.naturalWidth && image.naturalHeight ? Math.min(availableWidth / image.naturalWidth, availableHeight / image.naturalHeight) * image.naturalHeight : availableHeight; const fit = Math.min(arrowHeight * 52 / 44 * .48 / overlay.naturalWidth, arrowHeight * .60 / overlay.naturalHeight); ctx.drawImage(overlay, -overlay.naturalWidth * fit / 2, -overlay.naturalHeight * fit / 2, overlay.naturalWidth * fit, overlay.naturalHeight * fit); ctx.restore(); } ctx.fillStyle = invalid ? '#b84138' : selected ? '#007780' : '#5a7970'; ctx.font = 'bold 0.23px sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; if (definition.boardBehavior !== 'burrowingBlocker') ctx.fillText({ 1: '↓', 2: '→', 3: '↑', 4: '←' }[direction], col + footprint.width - .19, row + .2); if (selected) { ctx.lineWidth = .045; ctx.strokeStyle = '#07858c'; ctx.strokeRect(col + .018, row + .018, footprint.width - .036, footprint.height - .036); } ctx.restore(); } function draw() { const rect = $('viewport').getBoundingClientRect(), dpr = window.devicePixelRatio || 1; const width = Math.max(1, rect.width), height = Math.max(1, rect.height); if (canvas.width !== Math.round(width * dpr) || canvas.height !== Math.round(height * dpr)) { canvas.width = Math.round(width * dpr); canvas.height = Math.round(height * dpr); } ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, width, height); if (!state.level) return; const preview = state.view === 'preview', board = state.result?.board; $('canvas-empty').hidden = !preview || Boolean(board); if (preview && !board) { transform = null; return; } const columns = preview ? board.geometry.columns : state.level.width; const rows = preview ? board.geometry.rows : state.level.height; const angle = preview ? board.geometry.rotationDeg * Math.PI / 180 : 0; const cosine = Math.cos(angle), sine = Math.sin(angle); const boundsW = Math.abs(columns * cosine) + Math.abs(rows * sine); const boundsH = Math.abs(columns * sine) + Math.abs(rows * cosine); const scale = Math.min((width - 80) / (boundsW + 1), (height - 55) / (boundsH + 1), 65) * state.zoom; const x = width / 2 + state.pan.x, y = height / 2 + state.pan.y; transform = { columns, rows, angle, scale, x, y }; ctx.save(); ctx.translate(x, y); ctx.scale(scale, scale); ctx.rotate(angle); ctx.translate(-columns / 2, -rows / 2); if (preview && state.result.boundary) { ctx.beginPath(); state.result.boundary.forEach((point, index) => { const dx = (point.x - board.geometry.center.x) / board.geometry.cellSize; const dy = (point.y - board.geometry.center.y) / board.geometry.cellSize; const px = dx * cosine + dy * sine + columns / 2, py = -dx * sine + dy * cosine + rows / 2; if (index) ctx.lineTo(px, py); else ctx.moveTo(px, py); }); ctx.closePath(); ctx.strokeStyle = '#9badb7'; ctx.lineWidth = .035; ctx.setLineDash([.1,.1]); ctx.stroke(); ctx.setLineDash([]); } const valid = preview ? new Set(board.validCells) : null; for (let row = 0; row < rows; row++) for (let col = 0; col < columns; col++) { if (valid && !valid.has(col + ',' + row)) continue; ctx.fillStyle = (row + col) % 2 ? '#f9fbfa' : '#ffffff'; ctx.fillRect(col, row, 1, 1); ctx.strokeStyle = '#dce5e4'; ctx.lineWidth = .012; ctx.strokeRect(col, row, 1, 1); } ctx.fillStyle = '#8d9ba4'; ctx.font = '0.21px Consolas,monospace'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; for (let col = 0; col < columns; col++) ctx.fillText(col, col + .5, -.38); for (let row = 0; row < rows; row++) ctx.fillText(row, -.38, row + .5); const entities = displayedEntities(); const invalidEntries = new Set((state.result?.issues || []).filter(issue => issue.collection).map(issue => issue.collection + ':' + issue.entryIndex)); for (const entity of entities) { const selected = state.selected?.collection === entity.collection && state.selected?.index === entity.index; if (state.drag?.type === 'object' && selected && !preview && state.drag.moved) continue; drawEntity(entity.entry, selected, false, invalidEntries.has(entity.collection + ':' + entity.index)); } if (!preview && state.drag?.type === 'object' && state.drag.moved) drawEntity(state.drag.candidate, true, true, !state.drag.valid); if (!preview && state.material && state.hover) { const entry = [state.material.id, state.hover.col, state.hover.row, 2]; const candidate = clone(state.level); candidate[state.material.collection].push(entry); drawEntity(entry, false, true, Boolean(localIssues(candidate).length)); } ctx.restore(); } function gridPoint(event) { if (!transform) return null; const rect = canvas.getBoundingClientRect(), t = transform; const dx = (event.clientX - rect.left - t.x) / t.scale, dy = (event.clientY - rect.top - t.y) / t.scale; return { col: Math.floor(dx * Math.cos(t.angle) + dy * Math.sin(t.angle) + t.columns / 2), row: Math.floor(-dx * Math.sin(t.angle) + dy * Math.cos(t.angle) + t.rows / 2) }; } function hit(point) { return displayedEntities().reverse().find(entity => { const entry = entity.entry, footprint = definitionFor(entry)?.footprintsByOrientation[entry[3]]; return footprint?.cells.some(([dx, dy]) => entry[1] + dx === point.col && entry[2] + dy === point.row); }); } canvas.addEventListener('pointerdown', guarded(event => { if (state.busy || !state.level) return; if (pendingExtra()) applyExtra(); const point = gridPoint(event); if (!point) return; canvas.focus(); if (state.material && state.view === 'source' && event.button === 0) { const entry = [state.material.id, point.col, point.row, 2], candidate = clone(state.level); candidate[state.material.collection].push(entry); if (localIssues(candidate).length) { message('无法放置:对象越界或军械重叠', true); return; } mutate(() => { state.level[state.material.collection].push(entry); }); return; } const entity = event.button === 0 ? hit(point) : null; if (entity) { state.selected = { collection: entity.collection, index: entity.index }; state.material = null; if (state.view === 'source') state.drag = { type: 'object', start: point, before: clone(state.level), original: clone(entity.entry), moved: false }; render(); } else { state.selected = null; state.drag = { type: 'pan', x: event.clientX, y: event.clientY, original: { ...state.pan } }; render(); } canvas.setPointerCapture(event.pointerId); })); canvas.addEventListener('pointermove', event => { const point = gridPoint(event); if (!point) return; state.hover = point; $('coordinates').textContent = '列 ' + point.col + ' / 行 ' + point.row; const drag = state.drag; if (drag?.type === 'object') { const dx = point.col - drag.start.col, dy = point.row - drag.start.row; drag.candidate = clone(drag.original); shiftEntry(drag.candidate, dx, dy); drag.moved = dx !== 0 || dy !== 0; const candidate = clone(state.level); candidate[state.selected.collection][state.selected.index] = drag.candidate; drag.valid = !localIssues(candidate).length; } else if (drag?.type === 'pan') state.pan = { x: drag.original.x + event.clientX - drag.x, y: drag.original.y + event.clientY - drag.y }; draw(); }); canvas.addEventListener('pointerup', event => { const drag = state.drag; state.drag = null; if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId); if (drag?.type === 'object' && drag.moved) { if (drag.valid) { state.level[state.selected.collection][state.selected.index] = drag.candidate; changed(drag.before); } else message('移动已取消:对象越界或军械重叠', true); } draw(); }); canvas.addEventListener('pointercancel', () => { state.drag = null; draw(); }); canvas.addEventListener('pointerleave', () => { state.hover = null; draw(); }); canvas.addEventListener('contextmenu', event => event.preventDefault()); canvas.addEventListener('wheel', event => { event.preventDefault(); setZoom(state.zoom * (event.deltaY < 0 ? 1.1 : 1 / 1.1)); }, { passive: false }); // 移动巡逻对象时同步平移其源路径,不改变其他扩展参数。 function shiftEntry(entry, dx, dy) { entry[1] += dx; entry[2] += dy; const clips = Array.isArray(entry[4]?.aiClips) ? entry[4].aiClips : []; for (const clip of clips) for (const action of (Array.isArray(clip?.actions) ? clip.actions : [])) { if (action.method === 'movePath' && Array.isArray(action.params)) action.params = action.params.map(point => { const match = /^(-?\d+),(-?\d+)$/.exec(String(point)); return match ? (Number(match[1]) + dx) + ',' + (Number(match[2]) + dy) : point; }); } } function setZoom(value) { state.zoom = Math.max(.4, Math.min(3, value)); $('zoom-label').textContent = Math.round(state.zoom * 100) + '%'; draw(); } function rotate() { const entry = selectedEntry(); if (entry) mutate(() => { entry[3] = ({ 1: 4, 4: 3, 3: 2, 2: 1 })[entry[3]]; }); } function remove() { if (state.selected) mutate(() => { state.level[state.selected.collection].splice(state.selected.index, 1); state.selected = null; }); } function duplicate() { const entry = selectedEntry(); if (!entry || state.view !== 'source') return; for (let row = 0; row < state.level.height; row++) for (let col = 0; col < state.level.width; col++) { const next = clone(entry); shiftEntry(next, col - entry[1], row - entry[2]); const candidate = clone(state.level); candidate[state.selected.collection].push(next); if (!localIssues(candidate).length) { mutate(() => { state.level[state.selected.collection].push(next); state.selected.index = state.level[state.selected.collection].length - 1; }); return; } } throw new Error('棋盘内没有可复制的空位'); } function history(direction) { if (state.busy || state.view !== 'source') return; const source = direction === 'undo' ? state.history : state.future; const target = direction === 'undo' ? state.future : state.history; if (!source.length) return; target.push(clone(state.level)); state.level = source.pop(); state.selected = null; state.drag = null; state.sequence++; state.result = null; draftSave(); render(); scheduleValidation(); } $('previous').onclick = guarded(() => openLevel(state.level.displayLevel - 1)); $('next').onclick = guarded(() => openLevel(state.level.displayLevel + 1)); $('open').onclick = guarded(() => openLevel(Number($('level-number').value))); $('level-number').onkeydown = guarded(event => { if (event.key === 'Enter') return openLevel(Number($('level-number').value)); }); $('save').onclick = guarded(save); $('validate').onclick = guarded(async () => { if (pendingExtra()) applyExtra(); const result = await validate(); if (result) message(result.issues.length ? '校验发现问题' : '布局校验通过', Boolean(result.issues.length)); }); $('undo').onclick = () => history('undo'); $('redo').onclick = () => history('redo'); $('rotate').onclick = guarded(rotate); $('delete').onclick = guarded(remove); $('duplicate').onclick = guarded(duplicate); $('zoom-in').onclick = () => setZoom(state.zoom * 1.15); $('zoom-out').onclick = () => setZoom(state.zoom / 1.15); $('fit').onclick = () => { state.pan = { x: 0, y: 0 }; setZoom(1); }; $('select-tool').onclick = () => { state.material = null; renderLibrary(); render(); }; $('search').oninput = renderLibrary; $('library-tabs').onclick = event => { const button = event.target.closest('[data-kind]'); if (!button) return; state.kind = button.dataset.kind; document.querySelectorAll('[data-kind]').forEach(item => item.classList.toggle('active', item === button)); renderLibrary(); }; $('view-tabs').onclick = guarded(async event => { const button = event.target.closest('[data-view]'); if (!button || state.busy) return; if (pendingExtra()) applyExtra(); state.view = button.dataset.view; state.material = null; state.drag = null; state.pan = { x: 0, y: 0 }; renderLibrary(); render(); if (state.view === 'preview' && !state.result) await validate(); }); for (const [id, position] of [['object-type', 0], ['col', 1], ['row', 2], ['orientation', 3]]) { $(id).onchange = guarded(() => { const entry = selectedEntry(); if (!entry) return; const value = Number($(id).value); if (position === 1 || position === 2) { if (!Number.isSafeInteger(value)) throw new Error('请输入整数坐标'); mutate(() => shiftEntry(entry, position === 1 ? value - entry[1] : 0, position === 2 ? value - entry[2] : 0)); } else updateSelected(position, value); }); } $('properties').onsubmit = event => event.preventDefault(); $('apply-extra').onclick = guarded(applyExtra); for (const [id, property] of [['columns', 'width'], ['rows', 'height']]) $(id).onchange = guarded(() => { const value = Number($(id).value); if (!Number.isInteger(value) || value < 1 || value > 64) { render(); throw new Error('棋盘行列数必须是 1 到 64 的整数'); } mutate(() => { state.level[property] = value; }); }); $('restore-draft').onclick = guarded(() => { if (!state.draft || state.busy) return; const draft = state.draft; if (draft.level.displayLevel !== state.level.displayLevel || !Array.isArray(draft.level.characters) || !Array.isArray(draft.level.aoes)) throw new Error('草稿格式无效'); const before = clone(state.level); // 草稿保留原始版本号,磁盘已变化时仍由保存接口拦截覆盖。 state.level = { ...state.level, width: draft.level.width, height: draft.level.height, characters: draft.level.characters, aoes: draft.level.aoes }; state.revision = draft.revision; state.draft = null; state.view = 'source'; changed(before); message('已恢复本地草稿'); }); $('discard-draft').onclick = () => { if (confirm('删除此关卡的本地草稿?')) { localStorage.removeItem(draftKey()); state.draft = null; render(); } }; $('export').onclick = guarded(() => { if (!state.level) return; if (pendingExtra()) applyExtra(); const url = URL.createObjectURL(new Blob([JSON.stringify(state.level, null, 2) + '\n'], { type: 'application/json' })); const link = document.createElement('a'); link.href = url; link.download = (state.mode === 'ghost-king' ? '逐鹿关卡-' : '主线关卡-') + state.level.displayLevel + '.json'; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); message('已导出第 ' + state.level.displayLevel + ' 关'); }); $('import').onclick = () => { if (!state.busy) $('import-file').click(); }; $('import-file').onchange = guarded(async event => { const file = event.target.files[0]; event.target.value = ''; if (!file || !state.level || state.busy) return; if (file.size > 2 * 1024 * 1024) throw new Error('导入文件不能超过 2MB'); const number = state.level.displayLevel, revision = state.revision, initialLayout = layoutText(state.level), mode = state.mode; let imported; try { imported = JSON.parse(await file.text()); } catch { throw new Error('导入文件不是有效的 JSON'); } if (state.mode !== mode || state.level.displayLevel !== number || state.revision !== revision || layoutText(state.level) !== initialLayout) throw new Error('关卡已切换或修改,请重新导入'); if (!Array.isArray(imported.characters) || !Array.isArray(imported.aoes) || !Number.isInteger(imported.width) || !Number.isInteger(imported.height)) throw new Error('导入文件缺少棋盘尺寸或对象列表'); const candidate = { ...state.level, width: imported.width, height: imported.height, characters: imported.characters, aoes: imported.aoes }; const result = await api('/api/validate', { level: candidate }); if (state.mode !== mode || state.level.displayLevel !== number || state.revision !== revision || layoutText(state.level) !== initialLayout) throw new Error('关卡已切换或修改,请重新导入'); if (result.issues.length) throw new Error('导入校验失败:' + result.issues[0].message); if (!confirm('将导入布局应用到当前第 ' + number + ' 关?')) return; state.view = 'source'; state.selected = null; mutate(() => { state.level = candidate; }); message('布局已导入,尚未保存'); }); document.addEventListener('keydown', guarded(event => { if (state.busy) return; if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') { event.preventDefault(); return save(); } if (event.target.matches('input,textarea,select')) return; if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'z') { event.preventDefault(); history(event.shiftKey ? 'redo' : 'undo'); } if (event.key === 'Delete' || event.key === 'Backspace') { event.preventDefault(); remove(); } if (event.key.toLowerCase() === 'r') rotate(); if (event.key === 'Escape') { state.material = null; state.drag = null; state.selected = null; renderLibrary(); render(); } })); // 切换选择或执行工具前提交参数;非法 JSON 留在原处,不静默丢弃。 function commitPendingExtra(event) { if (event.target === $('extra') || event.target.closest('#extra-fields') || !pendingExtra()) return; try { applyExtra(); } catch (error) { event.preventDefault(); event.stopImmediatePropagation(); message(error.message, true); } } document.addEventListener('pointerdown', commitPendingExtra, true); document.addEventListener('click', commitPendingExtra, true); window.addEventListener('beforeunload', event => { if (dirty() || pendingExtra()) { event.preventDefault(); event.returnValue = ''; } }); new ResizeObserver(draw).observe($('viewport')); guarded(async () => { icons(); const bootstrap = await api('/api/bootstrap'); Object.assign(state, bootstrap); $('project-path').textContent = bootstrap.project; $('project-path').title = bootstrap.project; $('level-total').textContent = '/ ' + bootstrap.levelCount; $('level-number').max = bootstrap.levelCount; await openLevel(Number(new URLSearchParams(location.search).get('level') || 1)); })();