完善关卡转换工具:支持文件夹、合集和映射管理

This commit is contained in:
2026-11-24 15:13:48 +08:00
parent 9a6d6553fe
commit b176c79b61
7 changed files with 325 additions and 30 deletions
@@ -1,6 +1,5 @@
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);
@@ -15,15 +14,18 @@ const mapping = mappingFile ? JSON.parse(fs.readFileSync(mappingFile, 'utf8')) :
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: [] };
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: [] }; }
let results;
try { results = converter.convertDocument(JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')), mapping, zero); }
catch (error) { results = [{ ok: false, errors: ['读取或解析失败:' + error.message], warnings: [] }]; }
for (const result of results) {
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++; }
const output = converter.outputName(path.basename(file), result);
report.files.push({ file: path.basename(file), output, ...summary });
if (result.ok) { fs.writeFileSync(path.join(target, output), JSON.stringify(layout, null, 2), { flag: 'wx' }); report.success++; }
else report.failed++;
}
}
fs.writeFileSync(path.join(target, '转换报告.json'), JSON.stringify(report, null, 2));
console.log('转换完成:成功 ' + report.success + ',未转换 ' + report.failed + ';输出:' + target);
@@ -1,8 +1,92 @@
(function (root) {
'use strict';
const defaults = { animalGroup: { 1: { id: 1, collection: 'characters', length: 2, width: 1 } }, obstacleGroup: {} };
const defaults = {
animalGroup: {
1: { id: 1, collection: 'characters', length: 2, width: 1 },
100: { id: 2, collection: 'characters', length: 2, width: 1 }
}, obstacleGroup: {},
animals: {
pig: { id: 1, collection: 'characters', length: 2, width: 1 },
pigBomb: { id: 2, collection: 'characters', length: 2, width: 1, parameter: 'collisionBomb' },
pigClock: { id: 4, collection: 'characters', length: 2, width: 1, parameter: 'countdownBomb' },
duck: { id: 3, collection: 'characters', length: 1, width: 1 },
bear: { id: 5, collection: 'characters', length: 3, width: 2 }
}
};
const own = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
function convertCells(source, mapping = defaults) {
const unsupportedTypes = [];
const errors = [], warnings = ['按当前 animals/cells 转换,不读取 editor.sourceLevel 备份;每 2×2 源格合为 1 个目标格。',
'朝向按 d=0上/1右/2下/3左、行号保持递增转换;源文件标记 runtimeVerified=false 时仍需核对原工具画面。',
'跨项目对象采用近似玩法映射:pig→箭、pigBomb→爆破箭矢、pigClock→计时箭矢、duck→滚石、bear→张飞;须验收玩法。',
'计时参数写入对象冷却效果,但游戏仍会应用模板的 boomTime 及难度上限,最终时长可能不同。'];
const width = source?.cols / 2, height = source?.rows / 2;
const layout = { width, height, characters: [], aoes: [] }, occupied = new Set();
if (![width, height].every(n => Number.isInteger(n) && n > 0 && n <= 64)) errors.push('棋盘列数和行数必须是 2 到 128 的偶数');
if (source?.placement !== 'explicit_cells') errors.push('仅支持 placement=explicit_cells 的当前布局');
if (source?.levelMode) errors.push('非默认 levelMode 暂不支持');
if (!Array.isArray(source?.animals) || source.animals.length > 2048) errors.push('animals 必须是最多 2048 个对象的数组');
for (const key of Object.keys(source || {})) if (!['id', 'sourceImgid', 'cols', 'rows', 'cellSize', 'pigScale', 'levelMode', 'placement', 'levelUiName', 'animals', 'editor'].includes(key)) errors.push('尚未支持的关卡字段:' + key);
for (const [index, animal] of (Array.isArray(source?.animals) ? source.animals : []).entries()) {
try {
const rule = own(mapping?.animals || {}, animal?.type) ? mapping.animals[animal.type] : null;
if (!rule) {
if (!unsupportedTypes.some(item => item.type === animal?.type)) unsupportedTypes.push({ collection: 'animals', type: animal?.type });
throw new Error('类型 ' + animal?.type + ' 未适配,未配置当前布局映射');
}
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)) throw new Error('映射规则无效');
if (!Number.isInteger(animal.d) || animal.d < 0 || animal.d > 3) throw new Error('方向 d 必须是 0 到 3');
const col = animal.c / 2, row = animal.r / 2;
const sx = animal.d % 2 ? rule.length : rule.width, sy = animal.d % 2 ? rule.width : rule.length;
if (![col, row].every(Number.isInteger) || col < 0 || row < 0 || col + sx > width || row + sy > height) throw new Error('坐标无法对齐目标格或超出棋盘');
if (!Array.isArray(animal.cells) || animal.cells.length !== sx * sy * 4) throw new Error('实际占格不匹配目标对象;不能缩小或丢弃占格');
const cells = new Set();
for (const cell of animal.cells) {
if (!Number.isInteger(cell?.c) || !Number.isInteger(cell?.r) || cell.c < animal.c || cell.c >= animal.c + sx * 2 || cell.r < animal.r || cell.r >= animal.r + sy * 2) throw new Error('cells 不是映射对象所需的完整矩形');
cells.add(cell.c + ',' + cell.r);
}
if (cells.size !== animal.cells.length) throw new Error('cells 存在重复格');
const allowed = ['id', 'type', 'c', 'r', 'd', 'k', 'cells', 'sourceType', 'sourceId', 'sourceSkinIndex', 'sourceAnimalIndex', 'sourcePartIndex', 'sourceParts', 'sourceObstacleIndex'];
if (rule.parameter === 'collisionBomb') allowed.push('bombNum');
if (rule.parameter === 'countdownBomb') allowed.push('timerNum');
const unsupported = Object.keys(animal).filter(key => !allowed.includes(key));
if (unsupported.length) throw new Error('未支持的对象参数:' + unsupported.join('、'));
if (rule.parameter === 'collisionBomb' && animal.bombNum !== 3) throw new Error('本项目爆破箭矢固定为 3 次碰撞,不能保留 bombNum=' + animal.bombNum);
const entry = [rule.id, col, row, [3, 2, 1, 4][animal.d]];
let extra = rule.extra ? JSON.parse(JSON.stringify(rule.extra)) : null;
if (rule.parameter === 'countdownBomb') {
if (!Number.isFinite(animal.timerNum) || animal.timerNum < 0) throw new Error('timerNum 必须是非负数');
extra ||= {}; extra.addBuff ||= [];
if (!Array.isArray(extra.addBuff) || extra.addBuff.some(item => item?.buffId === 'cool-down')) throw new Error('映射附加参数中的倒计时与源参数冲突');
extra.addBuff.push({ addStack: 1, buffId: 'cool-down', duration: 0, durationSetTo: true, permanent: true, buffParam: { duration: animal.timerNum } });
}
if (extra) entry.push(extra);
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)) throw new Error('军械占格重叠:' + key);
occupied.add(key);
}
layout[rule.collection].push(entry);
} catch (error) { errors.push('animals[' + index + ']:' + error.message); }
}
return { ok: errors.length === 0, layout: errors.length ? null : layout, errors, warnings, unsupportedTypes };
}
function convertDocument(source, mapping = defaults, zero = 'north') {
if (source?.format !== 'zhuazhu-level-arrangement') return [{ name: '单关', ...convert(source, mapping, zero) }];
if (source.version !== 1 || !Array.isArray(source.slots) || !source.slots.length || source.slots.length > 20000 || !source.levels || typeof source.levels !== 'object' || Array.isArray(source.levels)) throw new Error('关卡编排合集版本或结构无效');
const slotIds = new Set();
return source.slots.map((slot, index) => {
const number = index + 1, name = '第' + String(number).padStart(3, '0') + '关';
if (!slot || typeof slot.slotId !== 'string' || !slot.slotId || slotIds.has(slot.slotId) || !own(source.levels, slot.slotId)) return { number, name, ok: false, layout: null, errors: ['编排位置缺少布局或 slotId 重复'], warnings: [] };
slotIds.add(slot.slotId);
return { number, name, sourceKey: slot.key, slotId: slot.slotId, ...convertCells(source.levels[slot.slotId], mapping) };
});
}
function convert(source, mapping = defaults, zero = 'north') {
if (source?.format === 'zhuazhu-level-arrangement') throw new Error('这是多关编排合集,请使用 convertDocument 按编排顺序转换');
if (source?.placement === 'explicit_cells') return convertCells(source, mapping);
const errors = [], warnings = ['转换假设:size 为格数,position 为居中棋盘中的占格左下角,角度按顺时针递增。尚未核对原游戏代码或画面,导入后须检查朝向和占格。'];
const unsupportedTypes = [];
const fail = message => errors.push(message);
const width = source?.size?.x, height = source?.size?.y;
const layout = { width, height, characters: [], aoes: [] };
@@ -14,8 +98,11 @@
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; }
const rule = own(mapping?.[group] || {}, object?.type) ? mapping[group][object.type] : null;
if (!rule) {
if (!unsupportedTypes.some(item => item.collection === group && item.type === object?.type)) unsupportedTypes.push({ collection: group, type: object?.type });
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;
@@ -45,9 +132,20 @@
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 };
if (source?.animalGroup?.some(object => object?.type === 100)) warnings.push('源类型 100 按编排合集中的爆破猪对应为爆破箭矢;目标固定 3 次碰撞,跨项目玩法仍需验收。');
return { ok: errors.length === 0, layout: errors.length ? null : layout, errors: [...new Set(errors)], warnings, unsupportedTypes };
}
const api = { convert, defaults };
function outputName(file, result) {
const stem = file.replace(/\.json$/i, '').replace(/[<>:"/\\|?*\x00-\x1f]/g, '_').slice(0, 80);
return stem + (result.number ? '-' + result.name : '') + '.json';
}
const targetTypes = [
[1, '箭', 2, 1], [2, '爆破箭矢', 2, 1], [3, '滚石', 1, 1], [4, '计时炸弹箭矢', 2, 1],
[5, '张飞', 3, 2], [6, '舞女', 2, 1], [7, '张角', 2, 1], [8, '黄忠', 2, 1],
[9, '赵云', 2, 1], [10, '攻城车', 2, 1], [11, '羽扇', 2, 1], [12, '木栅栏', 1, 1],
[13, '将旗', 1, 1], [14, '火船', 1, 1], [101, '拒马', 1, 1], [102, '铁索1×2', 2, 1], [103, '铁索2×2', 2, 2]
].map(([id, name, length, width]) => ({ id, name, length, width, collection: id >= 100 ? 'aoes' : 'characters' }));
const api = { convert, convertDocument, outputName, defaults, targetTypes };
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else root.PiggyConverter = api;
})(globalThis);
File diff suppressed because one or more lines are too long
@@ -9,7 +9,35 @@ 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);
const rawBomb = converter.convert({...source,animalGroup:[{...source.animalGroup[0],type:100}]});
assert(rawBomb.ok);assert.equal(rawBomb.layout.characters[0][0],2);
assert(!converter.convert({...source,animalGroup:[{...source.animalGroup[0],type:100,bombNum:2}]}).ok);
const unknown=converter.convert({...source,animalGroup:source.animalGroup.map(item=>({...item,type:112}))});
assert.deepEqual(unknown.unsupportedTypes,[{collection:'animalGroup',type:112}]);
assert(unknown.errors.every(message=>message.includes('类型 112 未适配')));
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('转换测试通过:四方向、坐标、源数据不变、字段白名单、未知类型、重叠、越界、特殊玩法及附加参数拦截。');
function animal(type = 'pig', d = 0) {
const sx = d % 2 ? 4 : 2, sy = d % 2 ? 2 : 4;
return { type, c: 2, r: 2, d, cells: Array.from({length:sx*sy}, (_,i)=>({c:2+i%sx,r:2+Math.floor(i/sx)})) };
}
const cells = {cols:16,rows:16,placement:'explicit_cells',animals:[animal()],editor:{sourceLevel:{invalid:true}}};
const snapshot = JSON.stringify(cells);
assert.deepEqual(converter.convert({...cells,animals:[animal('wolf')]}).unsupportedTypes,[{collection:'animals',type:'wolf'}]);
for(let d=0;d<4;d++) assert.deepEqual(converter.convert({...cells,animals:[animal('pig',d)]}).layout.characters[0],[1,1,1,[3,2,1,4][d]]);
assert.equal(JSON.stringify(cells),snapshot);
assert(converter.convert({...cells,animals:[{...animal('pigBomb'),bombNum:3}]}).ok);
assert(!converter.convert({...cells,animals:[{...animal('pigBomb'),bombNum:2}]}).ok);
const clock=converter.convert({...cells,animals:[{...animal('pigClock'),timerNum:60}]});
assert(clock.ok);assert.equal(clock.layout.characters[0][4].addBuff[0].buffParam.duration,60);
for(const value of [{...cells,cols:15},{...cells,animals:[{...animal(),c:3}]},{...cells,animals:[animal('wolf')]},{...cells,animals:[{...animal(),patrolEndWorld:{x:1,z:2}}]},{...cells,animals:[{...animal(),cells:Array(8).fill({c:2,r:2})}]},{...cells,animals:[{...animal('pigClock'),timerNum:-1}]}]) assert(!converter.convert(value).ok);
const bundle={format:'zhuazhu-level-arrangement',version:1,slots:[{slotId:'b',key:'B:3'},{slotId:'a',key:'A:1'}],levels:{a:{...cells,animals:[]},b:cells}};
const batch=converter.convertDocument(bundle);
assert.equal(batch.length,2);assert.equal(batch[0].sourceKey,'B:3');assert.equal(batch[0].layout.characters.length,1);assert.equal(batch[1].layout.characters.length,0);
assert.equal(converter.outputName('合集.json',batch[0]),'合集-第001关.json');
assert(!converter.convertDocument({...bundle,slots:[{slotId:'missing'}]})[0].ok);
assert(!converter.convertDocument({...bundle,slots:[{slotId:'a'},{slotId:'a'}]})[1].ok);
assert.throws(()=>converter.convertDocument({...bundle,version:99}));
console.log('合集测试通过:当前布局优先、顺序、二倍格换算、炸弹参数、重复编排、缺失布局和未知类型拦截。');
@@ -4,13 +4,32 @@
## 网页使用
双击 `转换工具.html`,选择一个或多个 Piggy Jam 关卡 JSON,点击“转换”。选择查看通过的文件,再下载当前单关 JSON;报告可以单独下载。原文件不会修改。
双击 `转换工具.html`,选择一个或多个 Piggy Jam 单关 JSON,或抓猪编辑器导出的编排合集 JSON(例如“文字挪车——前20关.json”),点击“转换”。单文件上限为 32MB。选择查看通过的关卡,再下载当前单关 JSON;也可下载批量结果 ZIP。原文件不会修改。
ZIP 解压后包含通过的单关 JSON 和转换报告。失败关卡不会导出,也不会压缩后续关卡编号。请在本项目“主线编排 → 从单关 JSON 导入”中逐关插入;此 ZIP 不是项目配置包,不能直接覆盖项目目录或作为完整编辑器数据包导入。
## 选择文件夹批量转换
在“源关卡文件夹”选择 `D:\Downloads\piggy-jam-config\levels\A`,点击“转换”,完成后下载批量结果 ZIP。需要支持目录选择的浏览器,建议使用 Chrome 或 Edge。
文件夹模式递归读取 JSON,跳过非 JSON 文件及 `LevelInfoConfig.json`,按文件名中的数字排序。也可选择上一级 `levels`:ZIP 中保留 A、B 等子目录,避免同名关卡覆盖。单个 JSON 的选择入口仍然保留,两种选择以最后一次选择为准。
页面显示通过和未转换数量;未适配类型仍然会阻止对应关卡导出,详细原因见转换报告。选择文件夹不会修改源文件,也不会增加对特殊玩法的支持。
## 合集转换规则
- 支持 `format=zhuazhu-level-arrangement`、`version=1`,严格按 `slots` 顺序读取 `levels` 中的当前 `animals/cells`,不读取 `editor.sourceLevel` 的旧备份。
- 每 2×2 源格合为 1 个目标格;坐标必须对齐,对象占格必须是完整矩形,不裁剪、不取整。`d=0/1/2/3` 暂按上/右/下/左解释,须与原工具画面对照验收。
- 默认近似映射:`pig` → 普通箭、`pigBomb` → 爆破箭、`pigClock` → 计时箭、`duck` → 滚石、`bear` → 张飞。跨项目行为不保证等价。
- 爆破次数只接受本项目支持的 3 次。计时时间写入对象附加参数,但模板中的 `boomTime` 和游戏难度上限仍可能覆盖最终时长。
- 巡逻狼 `wolf` 及未识别的附加参数会阻止整关导出,不会静默删除或改成普通箭。真实游戏表现需导入后验证。
- “源角度 0° 朝向”仅用于原始 Piggy Jam 数据;合集使用对象自身的 `d`。
得到的文件在本项目编辑器中可用于“导入布局 JSON”替换当前布局,也可在“主线编排 → 新增方式 → 从单关 JSON 导入”新增关卡。模板提供场景、难度、敌人和关卡级配置。
## 转换边界
## 原始 Piggy Jam 转换边界
- 默认仅将 `animalGroup.type=1` 转换为普通箭矢,不擅自推断其他类型。未知类型会阻止整关导出,不跳过对象,不降级为普通箭。
- 默认将 `animalGroup.type=1` 转换为普通箭矢,`type=100` 转换为爆破箭矢(参考编排合集对同一源类型的爆破猪映射;目标固定 3 次碰撞,需验收玩法)。其他未知类型会阻止整关导出,不跳过对象,不降级为普通箭。
- 当前坐标假设:`size` 是棋盘格数,`position` 是居中棋盘中的对象占格左下角,源坐标 Y 向上。坐标加半个棋盘尺寸得到目标锚点;不做取整、压缩或裁剪。此假设不是已确认的源游戏实现。
- 默认 0° 向上,90° 向右;可以调整零度朝向。此规则尚未从原游戏代码或运行画面确认,必须先对照原游戏检查一个上下左右均有对象的关卡,不能将批量通过理解为玩法等价。
- 映射规则中的 `length` 为沿朝向占格长度,`width` 为侧向宽度,必须与目标对象实际占格一致。工具不自带本项目完整对象目录,不能代替编辑器最终校验。
@@ -20,6 +39,14 @@
## 自定义映射
页面“源类型与目标对象”列出已知近似关系,每种源类型下面可通过下拉框选择本项目的军械或机关,或设为“未适配 / 不转换”。选择后同步更新映射 JSON,必须重新转换,旧下载结果会失效。转换中发现的未知类型也会加入列表,不会自动分配替代对象。
通过“新增映射”选择源分类、填写源类型、选择目标对象。原始单关源类型填写数字(如 `112`),合集源类型填写名称(如 `wolf`);同一分类内不允许重复新增。每条关系可删除,删除前会确认。删除的只是转换规则,不会修改原文件或跳过源对象;再次遇到该类型会提示未适配,并重新列入待适配列表。映射仅保留在当前页面,重新打开会恢复默认;需保留自定义规则时保存映射 JSON,后续粘贴到高级编辑框。
下拉框自动使用目标对象的分类及占格,不会自动迁移源对象的炸弹、路径等特殊参数。选择替代类型不是玩法等价承诺;参数或占格不兼容时仍然失败。页面同时保留高级 JSON 编辑入口。
失败时结果上方单独提示“112 类型未适配”或“wolf 类型未适配”;报告的 `unsupportedTypes` 记录去重后的源分类和类型,完整错误仍保留在 `errors` 中。
网页映射框可编辑,命令行可指定相同格式的 JSON 文件。键是源类型编号,`id` 是目标对象编号,`collection` 为 `characters` 或 `aoes`;可用 `extra` 配置固定目标附加参数。仅在确认源对象行为、大小和方向一致后添加映射。
## 批量输出
@@ -32,6 +59,12 @@ node .\convert.mjs "D:\Downloads\piggy-jam-config\levels\A" "D:\Downloads\piggy-
输出目录必须尚不存在。目录模式只处理 `level数字.json`,自动跳过 `LevelInfoConfig.json`。成功文件逐个输出,失败文件不输出;详细原因写入 `转换报告.json`。部分失败时退出码为 2。
也可直接将编排合集文件作为输入,自动按编排拆分:
```powershell
node .\convert.mjs "D:\Downloads\文字挪车——前20关.json" "D:\Downloads\文字挪车-转换结果"
```
```powershell
node .\convert.mjs "输入目录" "新建输出目录" "自定义映射.json" north
```
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Arjun Barrett
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -3,35 +3,147 @@
<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>
<style>
.mapping-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,230px),1fr));gap:12px;margin:12px 0}.mapping-row{border-bottom:1px solid #d3dce0;padding:8px 0}.mapping-row strong{display:block;overflow-wrap:anywhere}.mapping-row label{margin:8px 0}.mapping-row select{width:100%}.mapping-note{color:#586971;line-height:1.6}#failure{color:#a52a27;white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.6}#failure:empty{display:none}
</style>
<main><h1>关卡 JSON 转换</h1><section>
<label>源关卡 JSON <input id="files" type="file" accept=".json,application/json" multiple></label>
<label>源关卡文件夹 <input id="folder" type="file" webkitdirectory multiple></label>
<p id="summary" role="status">未选择文件</p>
<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>
<h2>源类型与目标对象</h2>
<form id="add-mapping">
<label>源分类 <select id="new-group"><option value="animalGroup">原始单关 · 动物</option><option value="obstacleGroup">原始单关 · 机关</option><option value="animals">合集 / 当前布局</option></select></label>
<label>源类型 <input id="new-type" type="text" maxlength="64" required aria-label="新增源类型"></label>
<label>目标对象 <select id="new-target"></select></label>
<button type="submit">新增映射</button>
</form>
<p id="mapping-status" role="status"></p>
<div id="mapping-list" class="mapping-grid"></div>
<p class="mapping-note">默认近似对应:pig → 箭、pigBomb → 爆破箭矢、pigClock → 计时炸弹箭矢、duck → 滚石、bear → 张飞。原始单关仅默认支持 1 → 箭、100 → 爆破箭矢;不能与合集类型混用。跨项目行为不保证等价。爆破箭矢固定 3 次碰撞,计时时长可能受模板和难度上限影响。选择替换类型不会自动适配源对象的特殊参数;占格或参数不兼容时仍会失败。</p>
<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>
<button id="convert">转换</button> <button id="download" disabled>下载当前单关 JSON</button> <button id="download-all" disabled>下载批量结果 ZIP</button> <button id="report" disabled>下载转换报告</button>
</section><section><h2>转换结果</h2><p id="failure" role="status"></p><pre id="result" role="status">未选择文件</pre></section><footer><a href="使用说明.md" target="_blank">使用说明</a></footer></main>
<script src="fflate.js"></script><script src="converter.cjs"></script><script>
'use strict';
const $=id=>document.getElementById(id);let results=[],generation=0;
const $=id=>document.getElementById(id);let results=[],generation=0,sourceFiles=[];
$('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):'没有可查看结果';}
const discoveredTypes=new Map();
const groupNames={animalGroup:'原始单关 · 动物',obstacleGroup:'原始单关 · 机关',animals:'合集 / 当前布局'};
for(const target of PiggyConverter.targetTypes)$('new-target').add(new Option(target.name+' · '+target.id+' · '+target.length+'×'+target.width,String(target.id)));
$('add-mapping').onsubmit=event=>{
event.preventDefault();
try{
const group=$('new-group').value,type=$('new-type').value.trim(),target=PiggyConverter.targetTypes.find(item=>item.id===Number($('new-target').value));
if(!type||['__proto__','prototype','constructor'].includes(type))throw Error('源类型无效');
if(group!=='animals'&&(!/^(0|[1-9]\d*)$/.test(type)||!Number.isSafeInteger(Number(type))))throw Error('原始单关的源类型必须是非负整数');
if(group==='animals'&&!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(type))throw Error('合集源类型须以字母开头,仅含字母、数字、下划线或连字符');
const mapping=JSON.parse($('mapping').value);if(!mapping||typeof mapping!=='object'||Array.isArray(mapping))throw Error('映射 JSON 必须是对象');
const current=mapping[group];if(current&&(!current||typeof current!=='object'||Array.isArray(current)))throw Error('源分类映射必须是对象');
if(Object.prototype.hasOwnProperty.call(current||{},type)&&current[type])throw Error('该源类型已有映射,请在列表中修改');
mapping[group]||={};const {name,...rule}=target;
const defaultRule=PiggyConverter.defaults[group]?.[type];if(defaultRule?.id===target.id&&defaultRule.parameter)rule.parameter=defaultRule.parameter;
mapping[group][type]=rule;discoveredTypes.set(group+':'+type,{collection:group,type});
$('mapping').value=JSON.stringify(mapping,null,2);invalidate();renderMappings();$('new-type').value='';$('mapping-status').textContent='已新增 '+groupNames[group]+' · '+type+' → '+target.name+',请重新转换';
}catch(error){$('mapping-status').textContent='新增失败:'+error.message;}
};
function renderMappings(){
let mapping;try{mapping=JSON.parse($('mapping').value);}catch{return;}
const rows=new Map(discoveredTypes);
for(const group of Object.keys(groupNames))for(const type of Object.keys(mapping?.[group]||{}))rows.set(group+':'+type,{collection:group,type});
const elements=[];
for(const {collection,type} of rows.values()){
const row=document.createElement('div');row.className='mapping-row';
const heading=document.createElement('strong');heading.textContent=groupNames[collection]+' · '+type;
const label=document.createElement('label');label.append('目标对象');
const select=document.createElement('select');select.setAttribute('aria-label',collection+' '+type+' 目标对象');select.dataset.group=collection;select.dataset.type=type;
select.add(new Option('未适配 / 不转换',''));
for(const target of PiggyConverter.targetTypes)select.add(new Option(target.name+' · '+target.id+' · '+target.length+'×'+target.width,String(target.id)));
const rule=mapping?.[collection]?.[type];
if(rule&&!PiggyConverter.targetTypes.some(target=>target.id===rule.id))select.add(new Option('自定义编号 '+rule.id,String(rule.id)));
select.value=rule?String(rule.id):'';
select.onchange=()=>{
try{
const current=JSON.parse($('mapping').value);if(!current||typeof current!=='object'||Array.isArray(current))throw Error('映射 JSON 必须是对象');
current[collection]||={};
if(!select.value)delete current[collection][type];
else{
const target=PiggyConverter.targetTypes.find(item=>item.id===Number(select.value)),previous=current[collection][type];
const next={...previous,id:target.id,collection:target.collection,length:target.length,width:target.width};
if(previous?.id!==target.id)delete next.parameter;
const defaultRule=PiggyConverter.defaults[collection]?.[type];
if(defaultRule?.id===target.id&&defaultRule.parameter)next.parameter=defaultRule.parameter;
current[collection][type]=next;
}
discoveredTypes.set(collection+':'+type,{collection,type});$('mapping').value=JSON.stringify(current,null,2);invalidate();renderMappings();
}catch(error){$('result').textContent='修改映射失败:'+error.message;}
};
const remove=document.createElement('button');remove.type='button';remove.textContent='删除映射';remove.setAttribute('aria-label','删除 '+collection+' '+type+' 映射');
remove.onclick=()=>{
if(!confirm('删除 '+type+' 的映射?不会删除源对象,再次转换时该类型将提示未适配。'))return;
try{
const current=JSON.parse($('mapping').value);if(current?.[collection])delete current[collection][type];
discoveredTypes.delete(collection+':'+type);$('mapping').value=JSON.stringify(current,null,2);invalidate();renderMappings();$('mapping-status').textContent='已删除 '+groupNames[collection]+' · '+type+' 的映射,请重新转换';
}catch(error){$('mapping-status').textContent='删除失败:'+error.message;}
};
label.append(select);row.append(heading,label,remove);elements.push(row);
}
$('mapping-list').replaceChildren(...elements);
}
renderMappings();
function invalidate(){generation++;results=[];$('failure').textContent='';$('selected').replaceChildren();$('download-all').disabled=$('download').disabled=$('report').disabled=true;$('result').textContent='请点击转换';}
for(const id of ['zero','mapping'])$(id).addEventListener('change',invalidate);
function choose(id){
const chosen=Array.from($(id).files);
if(!chosen.length)return;
$(id==='files'?'folder':'files').value='';
sourceFiles=chosen.filter(file=>/\.json$/i.test(file.name)&&!/^LevelInfoConfig\.json$/i.test(file.name))
.sort((a,b)=>(a.webkitRelativePath||a.name).localeCompare(b.webkitRelativePath||b.name,'zh-CN',{numeric:true}));
invalidate();
$('summary').textContent='已选择 '+sourceFiles.length+' 个 JSON,跳过 '+(chosen.length-sourceFiles.length)+' 个其他文件';
}
$('files').addEventListener('change',()=>choose('files'));
$('folder').addEventListener('change',()=>choose('folder'));
$('mapping').addEventListener('input',invalidate);
$('mapping').addEventListener('change',renderMappings);
function show(){
const item=results[$('selected').value];$('download').disabled=!item?.ok;
const types=(item?.unsupportedTypes||[]).map(entry=>entry.collection+':'+entry.type+' 类型未适配');
$('failure').textContent=item&&!item.ok?(types.length?'此关未转换:\n'+types.join('\n')+'\n未导出该关,未跳过任何对象。':'此关未转换:\n'+(item.errors||[]).join('\n')):'';
$('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=[];
const current=++generation;$('failure').textContent='';$('convert').disabled=true;$('download-all').disabled=$('download').disabled=$('report').disabled=true;results=[];
try{
const mapping=JSON.parse($('mapping').value),zero=$('zero').value,files=Array.from($('files').files);
const mapping=JSON.parse($('mapping').value),zero=$('zero').value,files=sourceFiles.slice();
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});
for(const [index,file] of files.entries()){
if(current!==generation)return;
$('summary').textContent='正在转换 '+(index+1)+' / '+files.length;
let items;try{if(file.size>32*1024*1024)throw Error('文件不能超过 32MB');const text=await file.text();if(current!==generation)return;items=PiggyConverter.convertDocument(JSON.parse(text.replace(/^\uFEFF/,'')),mapping,zero);}catch(error){items=[{ok:false,errors:['转换失败:'+error.message]}];}
const folders=(file.webkitRelativePath||'').split('/').slice(1,-1).map(part=>PiggyConverter.outputName(part+'.json',{}).slice(0,-5).replace(/^\.+$/,'_'));
for(const item of items){converted.push({file:file.webkitRelativePath||file.name,output:[...folders,PiggyConverter.outputName(file.name,item)].join('/'),...item});for(const unknown of item.unsupportedTypes||[])discoveredTypes.set(unknown.collection+':'+unknown.type,unknown);}
if(index%20===19)await new Promise(resolve=>setTimeout(resolve,0));
}
if(current!==generation)return;results=converted;$('selected').replaceChildren(...results.map((item,index)=>new Option((item.ok?'通过 · ':'未转换 · ')+item.file,index)));$('report').disabled=false;show();
if(current!==generation)return;results=converted;renderMappings();$('selected').replaceChildren(...results.map((item,index)=>new Option((item.ok?'通过 · ':'未转换 · ')+(item.number?item.name+' · ':'')+item.file,index)));$('report').disabled=false;$('download-all').disabled=!results.some(item=>item.ok);$('summary').textContent='共 '+results.length+' 关,通过 '+results.filter(item=>item.ok).length+' 关,未转换 '+results.filter(item=>!item.ok).length+' 关';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);};
function save(name,blob){const url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
function download(name,data){save(name,new Blob([JSON.stringify(data,null,2)],{type:'application/json'}));}
$('download').onclick=()=>{const item=results[$('selected').value];if(item?.ok)download(item.output.split('/').pop(),item.layout);};
$('download-all').onclick=()=>{
try{
const files=Object.create(null);
for(const item of results.filter(item=>item.ok)){
if(Object.hasOwn(files,item.output))throw Error('输出文件重名,请分别转换同名源文件');
files[item.output]=fflate.strToU8(JSON.stringify(item.layout,null,2));
}
files['转换报告.json']=fflate.strToU8(JSON.stringify(results.map(({layout,...report})=>report),null,2));
save('关卡转换结果.zip',new Blob([fflate.zipSync(files,{level:6})],{type:'application/zip'}));
}catch(error){$('result').textContent='批量下载失败:'+error.message;}
};
$('report').onclick=()=>download('转换报告.json',results.map(({layout,...report})=>report));
</script></html>