更新离线关卡编辑器,加入单关导入和抓猪关卡转换工具

This commit is contained in:
2026-11-24 11:14:04 +08:00
parent 7f83f146a4
commit 9a6d6553fe
13 changed files with 1372 additions and 1124 deletions
+1 -2
View File
@@ -511,8 +511,7 @@ $('import-file').onchange = guarded(async event => {
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 candidate = { ...state.level, ...MainlineWorkspace.importLayout(imported) };
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);
+61 -13
View File
@@ -6,11 +6,12 @@
element.innerHTML = '<i data-lucide="' + icon + '"></i>' + text; return element;
}
const manage = button('mainline-manage', '主线编排', 'list-ordered', '主线编排');
const importButton = button('package-import', '导入关卡数据包', 'folder-input');
const exportButton = button('package-export', '导出全部关卡数据包', 'package-open');
const importButton = button('package-import', '导入完整数据包 JSON', 'folder-input');
const exportButton = button('package-export', '导出完整数据包 JSON(可直接重新导入)', 'folder-output');
const projectExport = button('project-export', '导出项目文件包 ZIP', 'folder-down');
actions.insertBefore(manage, $('dirty')); actions.insertBefore(importButton, $('import')); actions.insertBefore(exportButton, $('export'));
actions.insertBefore(projectExport, exportButton);
actions.insertBefore(manage, $('dirty'));
actions.insertBefore(importButton, $('import')); actions.insertBefore(exportButton, $('import'));
actions.insertBefore(projectExport, $('validate'));
const helpButton = button('editor-help', '使用说明', 'circle-help'); actions.append(helpButton);
helpButton.onclick = () => { const help = $('help-dialog'); if (!help.open) help.showModal(); };
const exportDialog = document.createElement('dialog'); exportDialog.id = 'project-export-dialog'; exportDialog.setAttribute('aria-labelledby', 'project-export-title');
@@ -23,14 +24,17 @@
'<div class="mainline-summary"><strong id="mainline-count"></strong><span id="mainline-pending"></span></div>' +
'<input id="mainline-search" type="search" placeholder="搜索关卡号或来源 ID" aria-label="搜索主线关卡">' +
'<select id="mainline-list" size="12" aria-label="主线关卡列表"></select>' +
'<div class="mainline-row"><label>新增方式 <select id="mainline-kind"><option value="copy">复制选中关卡</option><option value="empty">空白布局</option></select></label>' +
'<div class="mainline-row"><label>新增方式 <select id="mainline-kind"><option value="copy">复制选中关卡</option><option value="empty">空白布局</option><option value="json">从单关 JSON 导入</option></select></label>' +
'<button id="mainline-add"><i data-lucide="plus"></i>新增至末尾</button><button id="mainline-insert"><i data-lucide="list-plus"></i>插入选中关卡之后</button></div>' +
'<div id="mainline-json-row" class="mainline-row" hidden><button id="mainline-json-choose" title="选择导出的单关 JSON 文件"><i data-lucide="file-up"></i>选择 JSON</button><span id="mainline-json-name"></span>' +
'<span id="mainline-json-template" title="新关卡的场景、难度、敌人和玩法元数据继承所选模板,JSON 仅提供布局"></span><input id="mainline-json-file" type="file" accept=".json,application/json" aria-label="新增关卡 JSON 文件" hidden></div>' +
'<div class="mainline-row"><button id="mainline-up" title="上移一关" aria-label="上移一关"><i data-lucide="arrow-up"></i></button><button id="mainline-down" title="下移一关" aria-label="下移一关"><i data-lucide="arrow-down"></i></button>' +
'<label>移动到第 <input id="mainline-target" type="number" min="1" value="1" aria-label="目标关卡号"> 关</label><button id="mainline-move"><i data-lucide="arrow-right-to-line"></i>移动</button>' +
'<button id="mainline-undo" title="撤销编排" aria-label="撤销编排"><i data-lucide="undo-2"></i></button><button id="mainline-remove"><i data-lucide="trash-2"></i>从主线移除</button></div>' +
'<p id="mainline-error" role="alert"></p><div class="mainline-footer"><button id="mainline-cancel">取消</button><button id="mainline-apply" class="primary"><i data-lucide="check"></i>应用编排</button></div>';
document.body.append(dialog); icons();
let draft, revision, selected, history = [], modified = false, initialModified = false, submitting = false;
let importedLayout = null, importedName = '', readingFile = false, generation = 0, validationOrder = [];
function redraw() {
draft.levels.forEach((level, index) => { level.displayLevel = index + 1; });
const search = $('mainline-search').value.trim().toLowerCase(), list = $('mainline-list'); list.replaceChildren();
@@ -45,16 +49,39 @@
const index = draft.order.indexOf(selected);
$('mainline-up').disabled = index <= 0; $('mainline-down').disabled = index < 0 || index === draft.order.length - 1;
$('mainline-remove').disabled = index < 0 || draft.order.length <= 1;
$('mainline-undo').disabled = !history.length; $('mainline-apply').disabled = !modified;
const importing = $('mainline-kind').value === 'json';
$('mainline-json-row').hidden = !importing;
$('mainline-json-name').textContent = readingFile ? '正在读取…' : importedName || '未选择文件';
$('mainline-json-template').textContent = index >= 0 ? '配置模板:第 ' + (index + 1) + ' 关 · 来源 ' + selected : '';
$('mainline-json-choose').disabled = readingFile;
$('mainline-add').disabled = $('mainline-insert').disabled = readingFile || (importing && !importedLayout);
$('mainline-undo').disabled = !history.length; $('mainline-apply').disabled = !modified || readingFile;
}
function setSubmitting(value) {
submitting = value;
dialog.querySelectorAll('button,input,select').forEach(element => { element.disabled = value; });
if (!value && dialog.open) redraw();
}
function remember() {
history.push({ draft: clone(draft), selected }); if (history.length > 20) history.shift(); modified = true; $('mainline-error').textContent = '';
}
function create(append) {
async function create(append) {
if (MainlineWorkspace.sourceOrder(draft).length >= 20000) throw new Error('来源库存最多支持 20000 关');
const index = draft.order.indexOf(selected); if (index < 0) throw new Error('请先选择模板关卡');
remember(); const id = Math.max(...MainlineWorkspace.sourceOrder(draft)) + 1, level = clone(draft.levels[index]);
const id = Math.max(...MainlineWorkspace.sourceOrder(draft)) + 1;
let level = clone(draft.levels[index]);
if ($('mainline-kind').value === 'json') {
if (readingFile || !importedLayout) throw new Error('请先选择单关 JSON 文件');
level = { ...level, ...clone(importedLayout) };
setSubmitting(true);
try {
// 尚未应用的新增关卡不在校验器中,使用它继承的已保存模板定位场景和规则。
const result = await api('/api/validate', { level: { ...level, displayLevel: validationOrder.indexOf(draft.templates[selected]) + 1 } });
if (result.issues.length) throw new Error('导入布局与所选模板不兼容:' + result.issues[0].message);
} finally { setSubmitting(false); }
}
if ($('mainline-kind').value === 'empty') { level.characters = []; level.aoes = []; }
remember();
const position = append ? draft.order.length : index + 1;
draft.templates[id] = draft.templates[selected]; draft.order.splice(position, 0, id); draft.levels.splice(position, 0, level);
selected = id; $('mainline-search').value = ''; $('mainline-target').value = position + 1; redraw();
@@ -65,11 +92,31 @@
if (index < 0 || index === target) return;
remember(); draft.order.splice(target, 0, draft.order.splice(index, 1)[0]); draft.levels.splice(target, 0, draft.levels.splice(index, 1)[0]); redraw();
}
const localGuard = action => () => { if (submitting) return; try { action(); } catch (error) { $('mainline-error').textContent = error.message; } };
const localGuard = action => async () => { if (submitting) return; try { await action(); } catch (error) { $('mainline-error').textContent = error.message; } };
function close() { if (!submitting && (!modified || confirm('编排尚未应用,确定放弃?'))) dialog.close(); }
$('mainline-close').onclick = close; $('mainline-cancel').onclick = close;
dialog.addEventListener('cancel', event => { event.preventDefault(); close(); });
dialog.addEventListener('keydown', event => event.stopPropagation());
dialog.addEventListener('close', () => { generation++; importedLayout = null; importedName = ''; readingFile = false; });
$('mainline-kind').onchange = redraw;
$('mainline-json-choose').onclick = () => { if (!submitting && !readingFile) $('mainline-json-file').click(); };
$('mainline-json-file').onchange = async event => {
const file = event.target.files[0]; event.target.value = '';
if (!file || submitting || readingFile || !dialog.open) return;
const currentGeneration = generation;
importedLayout = null; importedName = ''; readingFile = true; $('mainline-error').textContent = ''; redraw();
try {
if (file.size > 2 * 1024 * 1024) throw new Error('单关 JSON 文件不能超过 2MB');
let parsed;
try { parsed = JSON.parse(await file.text()); } catch { throw new Error('单关文件不是有效的 JSON'); }
if (currentGeneration !== generation || !dialog.open) return;
importedLayout = MainlineWorkspace.importLayout(parsed); importedName = file.name;
} catch (error) {
if (currentGeneration === generation && dialog.open) $('mainline-error').textContent = error.message;
} finally {
if (currentGeneration === generation && dialog.open) { readingFile = false; redraw(); }
}
};
$('mainline-list').onchange = () => { selected = Number($('mainline-list').value); $('mainline-target').value = draft.order.indexOf(selected) + 1; redraw(); };
$('mainline-search').oninput = redraw;
$('mainline-add').onclick = localGuard(() => create(true)); $('mainline-insert').onclick = localGuard(() => create(false));
@@ -111,21 +158,22 @@
setBusy(true);
try {
const result = await snapshot(); draft = result.package; revision = result.revision; selected = state.sourceLevel;
validationOrder = MainlineWorkspace.sourceOrder(draft); generation++; importedLayout = null; importedName = ''; readingFile = false;
history = []; modified = initialModified = dirty(); $('mainline-search').value = ''; $('mainline-error').textContent = '';
$('mainline-target').value = state.level.displayLevel; redraw(); dialog.showModal();
} finally { setBusy(false); }
});
$('mainline-apply').onclick = async () => {
if (submitting) return;
if (submitting || readingFile || !modified) return;
if (!window.offlineEditor && !confirm('将写入项目主线顺序、布局和新增关卡配置,并创建备份。现有玩家存档不会自动迁移,请确认发布安排。继续?')) return;
submitting = true; setBusy(true); dialog.querySelectorAll('button,input,select').forEach(element => { element.disabled = true; });
setSubmitting(true); setBusy(true);
try {
const number = draft.order.indexOf(selected) + 1;
const result = await api('/api/mainline', { package: draft, revision });
modified = false; dialog.close();
await refresh(number, '主线编排已应用,共 ' + draft.order.length + ' 关' + (result.backup ? ';备份:' + result.backup : ',请导出完整数据包交付'));
} catch (error) { $('mainline-error').textContent = error.message; }
finally { submitting = false; setBusy(false); dialog.querySelectorAll('button,input,select').forEach(element => { element.disabled = false; }); if (dialog.open) redraw(); }
finally { setSubmitting(false); setBusy(false); }
};
function download(bundle) {
const url = URL.createObjectURL(new Blob([JSON.stringify(bundle, null, 2)], { type: 'application/json' }));
@@ -134,7 +182,7 @@
exportButton.onclick = guarded(async () => {
if (state.busy || !state.level) return;
setBusy(true);
try { const result = await snapshot(); download(result.package); message('已导出完整数据包,包含主线顺序、新增关卡和当前布局'); }
try { const result = await snapshot(); download(result.package); message('已下载完整数据包 JSON,包含主线顺序、新增关卡和当前布局;可用“导入完整数据包 JSON”直接导入'); }
finally { setBusy(false); }
});
projectExport.onclick = () => { if (!state.busy && state.level) { exportDialog.returnValue = 'cancel'; exportDialog.showModal(); } };
+29 -16
View File
@@ -2113,14 +2113,12 @@ exports.remapContentUnlocks = remapContentUnlocks;
// 启动前的兼容初值;正式启动和工具读取均由 LevelSequence.json 覆盖。
exports.MAINLINE_TEMPLATE_SOURCES = {};
exports.PREVIOUS_REMOVED_MAINLINE_LEVELS = new Set([
90, 103, 120, 144, 152, 160, 175, 185, 202, 210, 225, 240, 253, 272,
291, 310, 329, 348, 360, 374, 388, 413, 427, 445, 462, 472, 477, 490,
506, 521, 534, 547, 558, 570, 599, 605, 635, 649, 662, 676, 687, 705,
727, 739, 753, 767, 778, 794, 808, 819, 832, 849, 866, 881, 894, 917,
930, 944, 958, 973, 981, 995, 1010, 1018, 1034, 1041, 1052,
90, 103, 120, 144, 152, 160, 175, 185, 202, 210, 225, 240, 253, 272, 291, 310, 329, 348, 360, 374, 388, 413, 427, 445, 462, 472, 477,
490, 506, 521, 534, 547, 558, 570, 599, 605, 635, 649, 662, 676, 687, 705, 727, 739, 753, 767, 778, 794, 808, 819, 832, 849, 866, 881,
894, 917, 930, 944, 958, 973, 981, 995, 1010, 1018, 1034, 1041, 1052,
]);
exports.MAINLINE_SOURCE_LEVELS = Object.freeze(Array.from({ length: 1070 }, (_, index) => index + 1));
exports.PREVIOUS_MAINLINE_SOURCE_LEVELS = Object.freeze(Array.from({ length: 1070 }, (_, index) => index + 1).filter(level => !exports.PREVIOUS_REMOVED_MAINLINE_LEVELS.has(level)));
exports.PREVIOUS_MAINLINE_SOURCE_LEVELS = Object.freeze(Array.from({ length: 1070 }, (_, index) => index + 1).filter((level) => !exports.PREVIOUS_REMOVED_MAINLINE_LEVELS.has(level)));
exports.MAINLINE_LEVEL_COUNT = exports.MAINLINE_SOURCE_LEVELS.length;
// 主线之外的来源追加在内部读取序列末尾,供逐鹿继续读取;不计入主线关数。
exports.CONTENT_SOURCE_LEVELS = exports.MAINLINE_SOURCE_LEVELS;
@@ -2129,18 +2127,21 @@ function configureMainlineSequence(order, templates, sourceCount = order.length)
exports.MAINLINE_TEMPLATE_SOURCES = Object.freeze({ ...templates });
exports.MAINLINE_LEVEL_COUNT = order.length;
const active = new Set(order);
exports.CONTENT_SOURCE_LEVELS = Object.freeze([...order, ...Array.from({ length: sourceCount }, (_, i) => i + 1).filter(id => !active.has(id))]);
exports.CONTENT_SOURCE_LEVELS = Object.freeze([
...order,
...Array.from({ length: sourceCount }, (_, i) => i + 1).filter((id) => !active.has(id)),
]);
}
function contentDisplayLevel(source) {
const index = exports.CONTENT_SOURCE_LEVELS.indexOf(source);
if (index < 0)
throw new Error('关卡来源不存在:' + source);
throw new Error("关卡来源不存在:" + source);
return index + 1;
}
function mainlineDisplayLevel(source) {
const index = exports.MAINLINE_SOURCE_LEVELS.indexOf(source);
if (index < 0)
throw new Error('主线来源关卡不存在:' + source);
throw new Error("主线来源关卡不存在:" + source);
return index + 1;
}
function mainlineUnlockLevel(sourceLevel) {
@@ -2149,24 +2150,36 @@ function mainlineUnlockLevel(sourceLevel) {
function mapMainlineUnlockLevel(sourceLevel, levels, templates) {
// 调序可能把高阶敌人提前;解锁必须不晚于最早达到来源门槛的模板关卡。
// 新增来源 ID 很大,但难度来自模板,不能因此提前解锁全部内容。
const index = levels.findIndex(level => (templates[level] ?? level) >= sourceLevel);
const index = levels.findIndex((level) => (templates[level] ?? level) >= sourceLevel);
return index < 0 ? levels.length : index + 1;
}
function remapMainlineRecords(records, sources = exports.MAINLINE_SOURCE_LEVELS) {
return Object.fromEntries(sources.map((sourceLevel, index) => [String(index + 1), records[String(sourceLevel)]]));
const result = {};
sources.forEach((sourceLevel, index) => {
result[String(index + 1)] = records[String(sourceLevel)];
});
return result;
}
function remapMainlineIndex(index) {
const firstAppearances = {};
for (const [group, entries] of Object.entries(index.firstAppearances || {})) {
firstAppearances[group] = Object.fromEntries(Object.entries(entries).map(([id, appearance]) => [id, {
...appearance, displayLevel: mainlineUnlockLevel(appearance.displayLevel),
}]));
const mappedEntries = {};
for (const [id, appearance] of Object.entries(entries)) {
mappedEntries[id] = {
...appearance,
displayLevel: mainlineUnlockLevel(appearance.displayLevel),
};
}
firstAppearances[group] = mappedEntries;
}
return { ...index, levelCount: exports.MAINLINE_LEVEL_COUNT, firstAppearances };
}
function remapContentUnlocks(entries) {
return entries.map(entry => entry.unlockLevel == null ? { ...entry } : {
...entry, unlockLevel: mainlineUnlockLevel(entry.unlockLevel),
return entries.map((entry) => entry.unlockLevel == null
? { ...entry }
: {
...entry,
unlockLevel: mainlineUnlockLevel(entry.unlockLevel),
});
}
+7
View File
@@ -53,6 +53,13 @@ header { flex-wrap: wrap; }
.has-overlay > img.entity-overlay { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 48%; height: 60%; object-fit: contain; pointer-events: none; }
.mainline-row label select { width: auto; max-width: 180px; }
#mainline-target { width: 80px; }
.file-actions :is(#package-import, #package-export) { color: #2463a5; background: #edf5ff; border-color: #b7cee9; }
.file-actions :is(#package-import, #package-export):hover { background: #deecfc; border-color: #7aa6d4; }
.file-actions :is(#import, #export) { color: #08766b; background: #edf8f3; border-color: #b4d8cd; }
.file-actions :is(#import, #export):hover { background: #dbf0e7; border-color: #73b6a1; }
.file-actions :is(#package-export, #export) { margin-right: 5px; }
#mainline-json-name { flex: 1 1 180px; min-width: 0; overflow-wrap: anywhere; font-size: 13px; color: var(--muted); }
#mainline-json-template { flex-basis: 100%; font-size: 12px; color: var(--muted); }
#mainline-error { font-size: 13px; color: #b42335; min-height: 18px; overflow-wrap: anywhere; }
.mainline-footer { justify-content: flex-end; border-top: 1px solid #e3e7ed; padding-top: 12px; }
@media (max-width: 600px) { dialog#mainline-dialog { padding: 14px; } #mainline-list { height: 240px; } .file-actions { flex-wrap: wrap; } }
+9 -1
View File
@@ -2,6 +2,14 @@
'use strict';
const copy = value => JSON.parse(JSON.stringify(value));
const fields = ['width', 'height', 'characters', 'aoes'];
function importLayout(input) {
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('请选择有效的单关 JSON 对象');
if (input.formatVersion !== undefined || Array.isArray(input.levels)) throw new Error('请选择导出的单关 JSON,不是完整关卡数据包');
if (!Number.isInteger(input.width) || !Number.isInteger(input.height) || input.width < 1 || input.height < 1 || input.width > 64 || input.height > 64) throw new Error('单关 JSON 的棋盘列数和行数必须是 1 到 64 的整数');
if (!Array.isArray(input.characters) || !Array.isArray(input.aoes)) throw new Error('单关 JSON 缺少军械或机关列表');
// 关卡编号、来源及玩法元数据由目标关卡或所选模板决定,文件只提供布局。
return Object.fromEntries(fields.map(field => [field, copy(input[field])]));
}
function create(data) {
return { formatVersion: 2, rulesVersion: data.rulesVersion, dataVersion: data.dataVersion,
order: [...data.order], templates: Object.fromEntries((data.sourceOrder || data.order).map(id => [id, id])), levels: copy(data.levels), archivedLevels: copy(data.archivedLevels || {}), ghostLayouts: copy(data.ghostLayouts || {}) };
@@ -43,7 +51,7 @@
result.archivedLevels = Object.fromEntries(Object.entries(archive).map(([id, level]) => [id, normalizeLevel(Number(id), level, Number(id), false)]));
return result;
}
const api = { create, normalize, sourceOrder, sourceLevel };
const api = { create, normalize, sourceOrder, sourceLevel, importLayout };
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else root.MainlineWorkspace = api;
})(globalThis);
+2 -1
View File
@@ -34,12 +34,13 @@
点击顶部“主线编排”,在列表中选择一关。可搜索显示关卡号或稳定来源 ID。
- 新增关卡:选择“复制选中关卡”或“空白布局”,点击“新增至末尾”。
- 从单关 JSON 新增:先选中用于继承配置的模板关卡,将“新增方式”切换为“从单关 JSON 导入”,点击“选择 JSON”读取以前导出的单关文件,再点击“新增至末尾”或“插入选中关卡之后”。布局按所选模板校验,通过后加入草稿,最后点击“应用编排”。可撤销或取消,不会覆盖原关卡。文件限 2MB,不接受完整数据包。
- 在第 7 与第 8 关之间插入:选中第 7 关,选择新增方式,点击“插入选中关卡之后”,再点击“应用编排”。新关成为第 8 关,原第 8 关及之后的显示编号自动顺延。
- 调整顺序:选择一关,点击上移、下移,或输入目标关卡号并点击“移动”。
- 移除关卡:选择一关,点击“从主线移除”并确认,再应用编排。后续关卡编号自动前移,主线至少保留一关。底层来源布局、难度、敌人和逐鹿引用保留,不会物理删除;误操作可在应用前撤销或取消。
- 撤销按钮仅撤销当前编排窗口中的操作;取消会丢弃未应用的编排。应用后会打开当前选中的关卡,可继续编辑棋盘。
新关继承模板的棋盘尺寸、场景、难度、敌人和玩法元数据。“空白布局”只清空军械、机关;“复制”保留模板布局。新增关卡暂不提供独立难度、敌人或场景配置界面,也不加入群雄逐鹿独立关卡序列。
新关继承模板的场景、难度、敌人和玩法元数据。“空白布局”继承模板尺寸并清空军械、机关;“复制”保留模板布局;“从单关 JSON 导入”使用文件的棋盘宽高、军械、机关及对象附加参数,不采用文件的关卡编号、来源 ID、难度或关卡级玩法元数据。主线和逐鹿导出的单关文件均可作为布局来源,但新关仍加入主线,不增加逐鹿关卡。新增关卡暂不提供独立难度、敌人或场景配置界面。
显示关卡号会变化,来源 ID 不变化,原关卡的布局、场景和难度随该关移动。来源库存最多支持 20000 关,移除的来源仍占库存,后续新增不会复用其 ID。当前关卡的未保存布局会随“应用编排”一起保存。整包导出只包含已应用的编排,不包含尚未应用的窗口操作。整包也保留已移除来源,用于逐鹿和再次导入。
@@ -0,0 +1,30 @@
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import converter from './converter.cjs';
const [input, output, mappingFile, zero = 'north'] = process.argv.slice(2);
if (!input || !output) {
console.error('用法:node convert.mjs 输入文件或目录 新建输出目录 [映射表.json] [north|east|south|west]');
process.exit(1);
}
const source = path.resolve(input), target = path.resolve(output);
if (fs.existsSync(target)) throw new Error('输出目录已存在,请指定新目录,避免覆盖已有文件');
if (target === source || target.startsWith(source + path.sep)) throw new Error('输出目录不能位于输入目录中');
const mapping = mappingFile ? JSON.parse(fs.readFileSync(mappingFile, 'utf8')) : converter.defaults;
const files = fs.statSync(source).isDirectory() ? fs.readdirSync(source).filter(name => /^level\d+\.json$/i.test(name)).sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).map(name => path.join(source, name)) : [source];
if (!files.length) throw new Error('输入目录没有 level数字.json 文件');
fs.mkdirSync(target, { recursive: true });
const report = { source, mapping: mappingFile || '默认:普通动物转箭矢', angleZero: zero, success: 0, failed: 0, files: [] };
for (const file of files) {
let result;
try { result = converter.convert(JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')), mapping, zero); }
catch (error) { result = { ok: false, errors: ['读取或解析失败:' + error.message], warnings: [] }; }
const { layout, ...summary } = result;
report.files.push({ file: path.basename(file), ...summary });
if (result.ok) { fs.writeFileSync(path.join(target, path.basename(file)), JSON.stringify(layout, null, 2)); report.success++; }
else report.failed++;
}
fs.writeFileSync(path.join(target, '转换报告.json'), JSON.stringify(report, null, 2));
console.log('转换完成:成功 ' + report.success + ',未转换 ' + report.failed + ';输出:' + target);
if (report.failed) process.exitCode = 2;
@@ -0,0 +1,53 @@
(function (root) {
'use strict';
const defaults = { animalGroup: { 1: { id: 1, collection: 'characters', length: 2, width: 1 } }, obstacleGroup: {} };
function convert(source, mapping = defaults, zero = 'north') {
const errors = [], warnings = ['转换假设:size 为格数,position 为居中棋盘中的占格左下角,角度按顺时针递增。尚未核对原游戏代码或画面,导入后须检查朝向和占格。'];
const fail = message => errors.push(message);
const width = source?.size?.x, height = source?.size?.y;
const layout = { width, height, characters: [], aoes: [] };
if (![width, height].every(n => Number.isInteger(n) && n > 0 && n <= 64)) fail('size.x 和 size.y 必须为 1 到 64 的整数');
if (!['north', 'east', 'south', 'west'].includes(zero)) fail('角度零点无效');
const vectors = { north: [0, 1, 3], east: [1, 0, 2], south: [0, -1, 1], west: [-1, 0, 4] };
const directions = Object.keys(vectors), occupied = new Set();
for (const group of ['animalGroup', 'obstacleGroup']) {
if (!Array.isArray(source?.[group])) { fail(group + ' 必须是数组'); continue; }
source[group].forEach((object, index) => {
const name = group + '[' + index + ']';
const rule = mapping?.[group]?.[object?.type];
if (!rule) { fail(name + ':类型 ' + object?.type + ' 未配置映射'); return; }
if (!['characters', 'aoes'].includes(rule.collection) || !Number.isSafeInteger(rule.id) || rule.id < 1 || ![rule.length, rule.width].every(n => Number.isInteger(n) && n > 0 && n <= 64)) { fail(name + ':映射规则无效'); return; }
if (!Number.isFinite(object.angle) || object.angle % 90 !== 0 || !Number.isFinite(object.position?.x) || !Number.isFinite(object.position?.y)) { fail(name + ':坐标或角度无效,角度必须为 90 的倍数'); return; }
const angle = ((object.angle % 360) + 360) % 360;
const direction = directions[(directions.indexOf(zero) + angle / 90) % 4];
const [dx, dy, orientation] = vectors[direction];
const sx = dx ? rule.length : rule.width, sy = dx ? rule.width : rule.length;
const col = object.position.x + width / 2;
const row = object.position.y + height / 2;
if (![col, row].every(Number.isInteger)) { fail(name + ':坐标无法对齐目标整数格;请核对坐标假设'); return; }
if (col < 0 || row < 0 || col + sx > width || row + sy > height) { fail(name + ':对象超出棋盘'); return; }
if (rule.collection === 'characters') {
for (let y = row; y < row + sy; y++) for (let x = col; x < col + sx; x++) {
const key = x + ',' + y;
if (occupied.has(key)) fail(name + ':军械占格重叠 ' + key);
occupied.add(key);
}
}
// 目标占格以包围盒左下角为锚点,负方向同样使用非负占格偏移。
const entry = [rule.id, col, row, orientation];
if (rule.extra) entry.push(JSON.parse(JSON.stringify(rule.extra)));
layout[rule.collection].push(entry);
const extras = Object.keys(object).filter(key => !['id', 'type', 'position', 'angle', 'skinIndex'].includes(key));
if (extras.length) fail(name + ':存在未支持的对象参数 ' + extras.join('、') + ',需人工确认转换规则');
});
}
if (source?.cloudContainer && Object.keys(source.cloudContainer).length) fail('存在云层配置 cloudContainer,暂不支持转换');
if (source?.openMole) fail('存在地鼠玩法 openMole,暂不支持转换');
if (source?.levelMode) fail('非默认 levelMode,暂不支持转换');
warnings.push('相机参数、皮肤编号、难度、奖励不导入;目标关卡级配置由编辑器所选模板继承。');
return { ok: errors.length === 0, layout: errors.length ? null : layout, errors: [...new Set(errors)], warnings };
}
const api = { convert, defaults };
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else root.PiggyConverter = api;
})(globalThis);
@@ -0,0 +1,15 @@
import assert from 'node:assert/strict';
import converter from './converter.cjs';
const source = { size: { x: 16, y: 16 }, animalGroup: [0, 90, 180, 270].map((angle, index) => ({ type: 1, angle, position: { x: -6 + index * 3, y: -3 } })), obstacleGroup: [] };
const before = JSON.stringify(source), result = converter.convert(source);
assert(result.ok);
assert.deepEqual(result.layout.characters.map(entry => entry[3]), [3, 2, 1, 4]);
assert.deepEqual(result.layout.characters[0], [1, 2, 5, 3]);
assert.equal(JSON.stringify(source), before);
assert.deepEqual(Object.keys(result.layout), ['width', 'height', 'characters', 'aoes']);
assert.equal(converter.convert(source, converter.defaults, 'east').layout.characters[0][3], 2);
for (const value of [null, {}, { ...source, size: { x: 65, y: 16 } }, { ...source, animalGroup: [{ ...source.animalGroup[0], type: 999 }] }, { ...source, animalGroup: [source.animalGroup[0], source.animalGroup[0]] }, { ...source, openMole: true }, { ...source, levelMode: 1 }, { ...source, cloudContainer: [1] }, { ...source, animalGroup: [{ ...source.animalGroup[0], boomTime: 3 }] }, { ...source, animalGroup: [{ ...source.animalGroup[0], angle: 12 }] }, { ...source, animalGroup: [{ ...source.animalGroup[0], position: { x: 100, y: 0 } }] }]) {
const invalid = converter.convert(value); assert(!invalid.ok); assert.equal(invalid.layout, null); assert(invalid.errors.length);
}
console.log('转换测试通过:四方向、坐标、源数据不变、字段白名单、未知类型、重叠、越界、特殊玩法及附加参数拦截。');
@@ -0,0 +1,37 @@
# 关卡 JSON 转换工具
独立工具,不依赖 Cocos、项目配置或关卡编辑器。整个目录可单独复制给其他人使用。
## 网页使用
双击 `转换工具.html`,选择一个或多个 Piggy Jam 关卡 JSON,点击“转换”。选择查看通过的文件,再下载当前单关 JSON;报告可以单独下载。原文件不会修改。
得到的文件在本项目编辑器中可用于“导入布局 JSON”替换当前布局,也可在“主线编排 → 新增方式 → 从单关 JSON 导入”新增关卡。模板提供场景、难度、敌人和关卡级配置。
## 转换边界
- 默认仅将 `animalGroup.type=1` 转换为普通箭矢,不擅自推断其他类型。未知类型会阻止整关导出,不跳过对象,不降级为普通箭。
- 当前坐标假设:`size` 是棋盘格数,`position` 是居中棋盘中的对象占格左下角,源坐标 Y 向上。坐标加半个棋盘尺寸得到目标锚点;不做取整、压缩或裁剪。此假设不是已确认的源游戏实现。
- 默认 0° 向上,90° 向右;可以调整零度朝向。此规则尚未从原游戏代码或运行画面确认,必须先对照原游戏检查一个上下左右均有对象的关卡,不能将批量通过理解为玩法等价。
- 映射规则中的 `length` 为沿朝向占格长度,`width` 为侧向宽度,必须与目标对象实际占格一致。工具不自带本项目完整对象目录,不能代替编辑器最终校验。
- 原对象的炸弹时间、路径、锁数量等附加字段,以及云层、地鼠和非默认模式暂不支持;出现这些数据会明确失败。
- 相机、皮肤不会进入目标文件。不会转换奖励、关卡难度、主线顺序等配置。
- 输出仅包含 `width`、`height`、`characters`、`aoes`。不会自动应用到游戏项目。
## 自定义映射
网页映射框可编辑,命令行可指定相同格式的 JSON 文件。键是源类型编号,`id` 是目标对象编号,`collection` 为 `characters` 或 `aoes`;可用 `extra` 配置固定目标附加参数。仅在确认源对象行为、大小和方向一致后添加映射。
## 批量输出
安装 Node.js 18 以上版本后运行(支持 Unicode 路径):
```powershell
node .\convert.mjs "D:\Downloads\piggy-jam-config\levels\A" "D:\Downloads\piggy-A-转换结果"
```
输出目录必须尚不存在。目录模式只处理 `level数字.json`,自动跳过 `LevelInfoConfig.json`。成功文件逐个输出,失败文件不输出;详细原因写入 `转换报告.json`。部分失败时退出码为 2。
```powershell
node .\convert.mjs "输入目录" "新建输出目录" "自定义映射.json" north
```
@@ -0,0 +1,37 @@
<!doctype html>
<html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>关卡 JSON 转换</title>
<style>
*{box-sizing:border-box}body{font:14px system-ui,sans-serif;color:#243238;background:#f5f7f8;margin:0}main{max-width:900px;margin:32px auto;padding:24px}h1{font-size:24px}section{padding:20px 0;border-top:1px solid #d3dce0}label{display:block;margin:12px 0}select,input,button{font:inherit;max-width:100%}select,button{padding:8px 12px;border:1px solid #aabcc2;border-radius:4px;background:white}button{cursor:pointer}button:disabled{opacity:.4;cursor:default}pre{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.6}textarea{width:100%;height:140px;font:13px monospace;border:1px solid #aabcc2;border-radius:4px;padding:12px}#download{background:#087d83;color:white}small{color:#586971}footer{padding-top:16px}a{color:#087d83}
</style>
<main><h1>关卡 JSON 转换</h1><section>
<label>源关卡 JSON <input id="files" type="file" accept=".json,application/json" multiple></label>
<label>待查看文件 <select id="selected"></select></label>
<label>源角度 0° 朝向 <select id="zero"><option value="north">上</option><option value="east">右</option><option value="south">下</option><option value="west">左</option></select></label>
<label>对象映射 JSON <textarea id="mapping" spellcheck="false" aria-label="对象映射 JSON"></textarea></label>
<button id="convert">转换</button> <button id="download" disabled>下载当前单关 JSON</button> <button id="report" disabled>下载转换报告</button>
</section><section><h2>转换结果</h2><pre id="result" role="status">未选择文件</pre></section><footer><a href="使用说明.md" target="_blank">使用说明</a></footer></main>
<script src="converter.cjs"></script><script>
'use strict';
const $=id=>document.getElementById(id);let results=[],generation=0;
$('mapping').value=JSON.stringify(PiggyConverter.defaults,null,2);
function invalidate(){generation++;results=[];$('download').disabled=$('report').disabled=true;$('result').textContent='请点击转换';}
for(const id of ['files','zero','mapping'])$(id).addEventListener('change',invalidate);
function show(){const item=results[$('selected').value];$('download').disabled=!item?.ok;$('result').textContent=item?JSON.stringify(item,null,2):'没有可查看结果';}
$('selected').onchange=show;
$('convert').onclick=async()=>{
const current=++generation;$('convert').disabled=true;$('download').disabled=$('report').disabled=true;results=[];
try{
const mapping=JSON.parse($('mapping').value),zero=$('zero').value,files=Array.from($('files').files);
if(!files.length)throw Error('请选择关卡 JSON');
const converted=[];
for(const file of files){
let item;try{if(file.size>2*1024*1024)throw Error('文件不能超过 2MB');item=PiggyConverter.convert(JSON.parse((await file.text()).replace(/^\uFEFF/,'')),mapping,zero);}catch(error){item={ok:false,errors:['转换失败:'+error.message]};}
converted.push({file:file.name,...item});
}
if(current!==generation)return;results=converted;$('selected').replaceChildren(...results.map((item,index)=>new Option((item.ok?'通过 · ':'未转换 · ')+item.file,index)));$('report').disabled=false;show();
}catch(error){$('result').textContent='转换失败:'+error.message;}finally{$('convert').disabled=false;}
};
function download(name,data){const url=URL.createObjectURL(new Blob([JSON.stringify(data,null,2)],{type:'application/json'})),a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
$('download').onclick=()=>{const item=results[$('selected').value];if(item?.ok)download('转换-'+item.file,item.layout);};
$('report').onclick=()=>download('转换报告.json',results.map(({layout,...report})=>report));
</script></html>
+4 -4
View File
File diff suppressed because one or more lines are too long
+1086 -1086
View File
File diff suppressed because it is too large Load Diff