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

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
@@ -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>