From 2aaad5e717845693bc3f84896f2b679746910df6 Mon Sep 17 00:00:00 2001 From: junFeng Date: Tue, 24 Nov 2026 16:11:44 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E7=A6=BB=E7=BA=BF=E7=BC=96?= =?UTF-8?q?=E8=BE=91=E5=99=A8=EF=BC=9A=E7=82=B8=E5=BC=B9=E6=95=B0=E5=80=BC?= =?UTF-8?q?=E6=A0=87=E6=B3=A8=E5=8F=8A=E5=8E=9F=E5=A7=8B=E5=85=B3=E5=8D=A1?= =?UTF-8?q?=E8=BD=AC=E6=8D=A2=E4=B9=9D=E7=A7=8D=E9=BB=98=E8=AE=A4=E6=98=A0?= =?UTF-8?q?=E5=B0=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app.js | 36 ++++- 使用说明.md | 2 + .../piggy-converter/convert.mjs | 10 +- .../piggy-converter/converter.cjs | 125 +++++------------- 抓猪关卡转换/piggy-converter/test.mjs | 76 +++++++---- .../piggy-converter/使用说明.md | 77 +++++------ .../piggy-converter/转换工具.html | 21 ++- 7 files changed, 165 insertions(+), 182 deletions(-) diff --git a/app.js b/app.js index ac9601f..a579523 100644 --- a/app.js +++ b/app.js @@ -224,11 +224,38 @@ function displayedEntities() { 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] })), + entry: [unit.artifactId, unit.col, unit.row, unit.sourceOrientation, unit.sourceExtra], unit })), ...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 }))); + const units = new Map((state.result?.board?.units || []).map(unit => [unit.id, unit])); + return ['characters', 'aoes'].flatMap(collection => state.level[collection].map((entry, index) => ({ collection, index, entry, + unit: collection === 'characters' ? units.get('u-' + String(index + 1).padStart(6, '0')) : null }))); +} +function bombLabel(definition, unit) { + if (definition.boardBehavior === 'collisionBomb') { + const count = unit?.collisionHp ?? definition.behaviorParams?.collisionHp; + return Number.isFinite(count) ? count + '次' : '待校验'; + } + if (definition.boardBehavior === 'countdownBomb') { + const duration = unit?.timer?.duration; + return Number.isFinite(duration) ? duration + '秒' : '待校验'; + } + return ''; +} +function drawBombLabel(definition, unit, col, row, footprint) { + const text = bombLabel(definition, unit); + if (!text) return; + ctx.save(); + ctx.translate(col + footprint.width / 2, row + footprint.height / 2 + .23); + // 局内预览会旋转棋盘,数字反向旋转以保持正向可读。 + ctx.rotate(-transform.angle); + ctx.font = 'bold 0.24px "Microsoft YaHei",sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + const width = Math.min(.92, Math.max(.56, ctx.measureText(text).width + .12)); + ctx.fillStyle = definition.boardBehavior === 'collisionBomb' ? '#8f3027' : '#075f68'; + ctx.fillRect(-width / 2, -.17, width, .34); + ctx.fillStyle = '#ffffff'; ctx.fillText(text, 0, 0, width - .1); + ctx.restore(); } function spriteAngle(definition, direction) { const footprint = definition.footprintsByOrientation[direction]; @@ -238,7 +265,7 @@ function spriteAngle(definition, direction) { || (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) { +function drawEntity(entry, selected = false, ghost = false, invalid = false, unit = null) { const definition = definitionFor(entry), footprint = definition?.footprintsByOrientation[entry[3]]; if (!footprint) return; const [id, col, row, direction] = entry; @@ -290,6 +317,7 @@ function drawEntity(entry, selected = false, ghost = false, invalid = false) { 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); + drawBombLabel(definition, unit, col, row, footprint); if (selected) { ctx.lineWidth = .045; ctx.strokeStyle = '#07858c'; ctx.strokeRect(col + .018, row + .018, footprint.width - .036, footprint.height - .036); } @@ -340,7 +368,7 @@ function draw() { 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)); + drawEntity(entity.entry, selected, false, invalidEntries.has(entity.collection + ':' + entity.index), entity.unit); } if (!preview && state.drag?.type === 'object' && state.drag.moved) drawEntity(state.drag.candidate, true, true, !state.drag.valid); if (!preview && state.material && state.hover) { diff --git a/使用说明.md b/使用说明.md index d307845..7f5fb52 100644 --- a/使用说明.md +++ b/使用说明.md @@ -19,6 +19,8 @@ 木栅栏选择“降下”后,源布局和局内预览显示降下图片与半透明状态;预览仅反映初始状态,不模拟游戏中的后续升降。 +爆破箭矢在棋盘上显示初始碰撞次数,计时炸弹箭矢显示校验后的实际初始倒计时(秒),源布局和局内预览均可查看。数字保持正向,不随箭矢朝向旋转。修改后尚未完成校验时,倒计时显示“待校验”,不会把后备配置误作最终时间;这里不是游戏运行中的实时倒计时。 + 关卡级倒计时 `progression.boomTime` 和封印锁血量 `progression.caveDesNum` 的优先级高于对象附加值,面板会提示当前来源;炸弹实际倒计时还可能受到难度限制,以校验后的实际值为准。这些控件不改变玩法的配置读取顺序。 高级附加配置 JSON 保留在折叠区,未识别字段和其他指令不会因表单修改而丢失。历史皮肤等当前玩法没有读取的字段只保留原数据,不提供生效控件。 diff --git a/抓猪关卡转换/piggy-converter/convert.mjs b/抓猪关卡转换/piggy-converter/convert.mjs index 1b69993..9b5ec95 100644 --- a/抓猪关卡转换/piggy-converter/convert.mjs +++ b/抓猪关卡转换/piggy-converter/convert.mjs @@ -16,16 +16,14 @@ 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 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) { + 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; - const output = converter.outputName(path.basename(file), result); + const output = converter.outputName(path.basename(file)); 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); diff --git a/抓猪关卡转换/piggy-converter/converter.cjs b/抓猪关卡转换/piggy-converter/converter.cjs index e33ee7a..868f95a 100644 --- a/抓猪关卡转换/piggy-converter/converter.cjs +++ b/抓猪关卡转换/piggy-converter/converter.cjs @@ -3,94 +3,28 @@ 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 } - } + 100: { id: 2, collection: 'characters', length: 2, width: 1 }, + 101: { id: 4, collection: 'characters', length: 2, width: 1 }, + 103: { id: 5, collection: 'characters', length: 3, width: 2 }, + // 依据源 LanguageConfig 匹配棋盘行为,大象按已确认的体型映射为张飞。 + 106: { id: 7, collection: 'characters', length: 2, width: 1 }, + 107: { id: 8, collection: 'characters', length: 2, width: 1 }, + 108: { id: 9, collection: 'characters', length: 2, width: 1 }, + 109: { id: 10, collection: 'characters', length: 2, width: 1 }, + 112: { id: 3, collection: 'characters', length: 1, width: 1 } + }, obstacleGroup: {} }; 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 为居中棋盘中的占格左下角,角度按顺时针递增。尚未核对原游戏代码或画面,导入后须检查朝向和占格。']; + if (source?.format || source?.placement || source?.slots || source?.animals) return { + ok: false, layout: null, errors: ['不支持该输入格式,仅支持 piggy-jam-config 原始关卡 JSON(size、animalGroup、obstacleGroup)'], warnings: [], unsupportedTypes: [] + }; + const errors = [], warnings = ['坐标转换:2 个源单位对应 1 个目标格,position 为对象中心,转换为目标占格左下角;此规则已对照 level1 目标布局,其他特殊类型仍须验收。']; const unsupportedTypes = []; const fail = message => errors.push(message); - const width = source?.size?.x, height = source?.size?.y; + const width = source?.size?.x / 2, height = source?.size?.y / 2; 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 (![width, height].every(n => Number.isInteger(n) && n > 0 && n <= 64)) fail('size.x 和 size.y 必须为 2 到 128 的偶数,转换后棋盘为 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(); @@ -109,8 +43,9 @@ 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; + // 源坐标以对象中心为锚点,先缩放,再减去目标包围盒半尺寸。 + const col = object.position.x / 2 + width / 2 - sx / 2; + const row = object.position.y / 2 + height / 2 - sy / 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') { @@ -122,9 +57,17 @@ } // 目标占格以包围盒左下角为锚点,负方向同样使用非负占格偏移。 const entry = [rule.id, col, row, orientation]; - if (rule.extra) entry.push(JSON.parse(JSON.stringify(rule.extra))); + const extra = rule.extra ? JSON.parse(JSON.stringify(rule.extra)) : {}; + const carriesTimer = group === 'animalGroup' && object.type === 101 && rule.collection === 'characters' && rule.id === 4; + if (carriesTimer && own(object, 'boomTime')) { + if (!Number.isFinite(object.boomTime) || object.boomTime < 0) { fail(name + ':boomTime 必须为非负有限数字'); return; } + if (extra.addBuff !== undefined && !Array.isArray(extra.addBuff)) { fail(name + ':映射附加参数 addBuff 必须为数组'); return; } + if (extra.addBuff?.some(buff => buff?.buffId === 'cool-down')) { fail(name + ':映射中的 cool-down 与源 boomTime 冲突,请移除重复计时配置'); return; } + extra.addBuff = [...(extra.addBuff || []), {buffId:'cool-down',buffParam:{duration:object.boomTime}}]; + } + if (rule.extra || Object.keys(extra).length) entry.push(extra); layout[rule.collection].push(entry); - const extras = Object.keys(object).filter(key => !['id', 'type', 'position', 'angle', 'skinIndex'].includes(key)); + const extras = Object.keys(object).filter(key => !['id', 'type', 'position', 'angle', 'skinIndex'].includes(key) && !(carriesTimer && key === 'boomTime')); if (extras.length) fail(name + ':存在未支持的对象参数 ' + extras.join('、') + ',需人工确认转换规则'); }); } @@ -132,12 +75,14 @@ if (source?.openMole) fail('存在地鼠玩法 openMole,暂不支持转换'); if (source?.levelMode) fail('非默认 levelMode,暂不支持转换'); warnings.push('相机参数、皮肤编号、难度、奖励不导入;目标关卡级配置由编辑器所选模板继承。'); - if (source?.animalGroup?.some(object => object?.type === 100)) warnings.push('源类型 100 按编排合集中的爆破猪对应为爆破箭矢;目标固定 3 次碰撞,跨项目玩法仍需验收。'); + if (source?.animalGroup?.some(object => object?.type === 100)) warnings.push('源类型 100 近似对应为爆破箭矢;目标固定 3 次碰撞,跨项目玩法仍需验收。'); + if (source?.animalGroup?.some(object => object?.type === 101 && mapping?.animalGroup?.[101]?.id === 4)) warnings.push('计时狮子的 boomTime 写入 cool-down 附加参数;目标模板 progression.boomTime 优先于此参数,且时长达到 180 秒时可能受目标难度上限限制,导入后须核对最终倒计时。'); + if (source?.animalGroup?.some(object => object?.type === 103 && mapping?.animalGroup?.[103]?.id === 5)) warnings.push('大象转换为占格 3×2 的张飞,保留棋盘占格;目标战斗能力采用张飞配置,不代表源游戏能力。'); return { ok: errors.length === 0, layout: errors.length ? null : layout, errors: [...new Set(errors)], warnings, unsupportedTypes }; } - function outputName(file, result) { + function outputName(file) { const stem = file.replace(/\.json$/i, '').replace(/[<>:"/\\|?*\x00-\x1f]/g, '_').slice(0, 80); - return stem + (result.number ? '-' + result.name : '') + '.json'; + return stem + '.json'; } const targetTypes = [ [1, '箭', 2, 1], [2, '爆破箭矢', 2, 1], [3, '滚石', 1, 1], [4, '计时炸弹箭矢', 2, 1], @@ -145,7 +90,7 @@ [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 }; + const api = { convert, outputName, defaults, targetTypes }; if (typeof module !== 'undefined' && module.exports) module.exports = api; else root.PiggyConverter = api; })(globalThis); diff --git a/抓猪关卡转换/piggy-converter/test.mjs b/抓猪关卡转换/piggy-converter/test.mjs index 0cb9e96..b528b74 100644 --- a/抓猪关卡转换/piggy-converter/test.mjs +++ b/抓猪关卡转换/piggy-converter/test.mjs @@ -1,43 +1,65 @@ 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 positions = [{x:-5,y:-4},{x:-2,y:-3},{x:1,y:-4},{x:4,y:-3}]; +const source = { size: { x: 16, y: 16 }, animalGroup: [0, 90, 180, 270].map((angle, index) => ({ type: 1, angle, position: positions[index] })), 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.deepEqual(result.layout.characters[0], [1, 1, 1, 3]); +assert.equal(result.layout.width,8); +assert.equal(result.layout.height,8); 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); +assert.equal(converter.convert({...source,animalGroup:[{type:1,angle:0,position:{x:-2,y:-3}}]}, 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 未适配'))); +const unknown=converter.convert({...source,animalGroup:source.animalGroup.map(item=>({...item,type:120}))}); +assert.deepEqual(unknown.unsupportedTypes,[{collection:'animalGroup',type:120}]); +assert(unknown.errors.every(message=>message.includes('类型 120 未适配'))); +for (const [type,id] of [[101,4],[103,5],[106,7],[107,8],[108,9],[109,10],[112,3]]) { + for (const [index,angle] of [0,90,180,270].entries()) { + const position=type===112?{x:-5,y:-5}:type===103?(index%2?{x:-3,y:-4}:{x:-4,y:-3}):positions[index]; + const input={...source,animalGroup:[{type,angle,position}]}; + const saved=JSON.stringify(input), converted=converter.convert(input); + assert(converted.ok,JSON.stringify(converted.errors)); + assert.equal(converted.layout.characters[0][0],id); + assert.equal(converted.layout.characters[0][3],[3,2,1,4][index]); + assert.equal(JSON.stringify(input),saved); + assert(!converter.convert({...input,animalGroup:[{...input.animalGroup[0],inBubble:true}]}).ok); + } +} +for(const type of [102,104,105,110,111,113,115,120,122,124,125]) { + const unmapped=converter.convert({...source,animalGroup:[{...source.animalGroup[0],type}]}); + assert(!unmapped.ok);assert.deepEqual(unmapped.unsupportedTypes,[{collection:'animalGroup',type}]); +} +assert.deepEqual(converter.defaults.obstacleGroup,{}); +assert.deepEqual(Object.keys(converter.defaults.animalGroup),['1','100','101','103','106','107','108','109','112']); +const timerSource={...source,animalGroup:[{type:101,angle:0,position:positions[0],boomTime:300}]}; +const timerBefore=JSON.stringify(timerSource),timer=converter.convert(timerSource); +assert(timer.ok); +assert.deepEqual(timer.layout.characters[0][4],{addBuff:[{buffId:'cool-down',buffParam:{duration:300}}]}); +assert.equal(JSON.stringify(timerSource),timerBefore); +assert(timer.warnings.some(message=>message.includes('progression.boomTime'))); +for(const boomTime of [-1,'300',null,Infinity])assert(!converter.convert({...timerSource,animalGroup:[{...timerSource.animalGroup[0],boomTime}]}).ok); +const changedMapping=JSON.parse(JSON.stringify(converter.defaults));changedMapping.animalGroup[101]={...changedMapping.animalGroup[101],id:1}; +assert(!converter.convert(timerSource,changedMapping).ok); +const conflictMapping=JSON.parse(JSON.stringify(converter.defaults));conflictMapping.animalGroup[101].extra={addBuff:[{buffId:'cool-down',buffParam:{duration:10}}]}; +assert(!converter.convert(timerSource,conflictMapping).ok); +assert.equal(conflictMapping.animalGroup[101].extra.addBuff[0].buffParam.duration,10); +console.log('默认映射测试通过:九种映射、四方向、大象及小鸡占位、计时参数转换与冲突拦截。'); 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)})) }; +assert.deepEqual(Object.keys(converter.defaults), ['animalGroup', 'obstacleGroup']); +for (const value of [{format:'zhuazhu-level-arrangement',version:1,slots:[],levels:{}},{placement:'explicit_cells',cols:16,rows:16,animals:[]},{...source,animals:[]}]) { + const result=converter.convert(value);assert(!result.ok);assert.equal(result.layout,null);assert(result.errors[0].includes('仅支持 piggy-jam-config')); } -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('合集测试通过:当前布局优先、顺序、二倍格换算、炸弹参数、重复编排、缺失布局和未知类型拦截。'); +assert.equal(converter.outputName('level3.json'),'level3.json'); +const level1 = {size:{x:16,y:16},obstacleGroup:[],animalGroup:[[-2,-3,270],[1,-2,0],[3,-2,180],[-1,0,0],[1,2,0],[-2,3,270],[3,2,180],[-3,0,0]].map(([x,y,angle])=>({type:1,position:{x,y},angle}))}; +assert.deepEqual(converter.convert(level1).layout, {width:8,height:8,characters:[[1,2,2,4],[1,4,2,3],[1,5,2,1],[1,3,3,3],[1,4,4,3],[1,2,5,4],[1,5,4,1],[1,2,3,3]],aoes:[]}); +assert(!converter.convert({...source,animalGroup:[{type:1,angle:0,position:{x:-4,y:-4}}]}).ok); +console.log('level1 回归通过:中心坐标和二比一缩放,无法对齐的坐标拒绝导出。'); +console.log('输入范围测试通过:拒绝合集和当前布局,仅保留原始关卡格式。'); diff --git a/抓猪关卡转换/piggy-converter/使用说明.md b/抓猪关卡转换/piggy-converter/使用说明.md index cafcb21..feefaf9 100644 --- a/抓猪关卡转换/piggy-converter/使用说明.md +++ b/抓猪关卡转换/piggy-converter/使用说明.md @@ -1,70 +1,63 @@ # 关卡 JSON 转换工具 -独立工具,不依赖 Cocos、项目配置或关卡编辑器。整个目录可单独复制给其他人使用。 +独立工具,不依赖 Cocos 或关卡编辑器,可将整个目录复制给策划使用。仅支持 piggy-jam-config 原始关卡数据(`size`、`animalGroup`、`obstacleGroup`),不再支持编排合集及 `explicit_cells` 当前布局格式。 ## 网页使用 -双击 `转换工具.html`,选择一个或多个 Piggy Jam 单关 JSON,或抓猪编辑器导出的编排合集 JSON(例如“文字挪车——前20关.json”),点击“转换”。单文件上限为 32MB。选择查看通过的关卡,再下载当前单关 JSON;也可下载批量结果 ZIP。原文件不会修改。 +双击 `转换工具.html`,选择一个或多个原始关卡 JSON,或选择关卡文件夹,再点击“转换”。单文件上限为 32MB。原文件不会修改。 -ZIP 解压后包含通过的单关 JSON 和转换报告。失败关卡不会导出,也不会压缩后续关卡编号。请在本项目“主线编排 → 从单关 JSON 导入”中逐关插入;此 ZIP 不是项目配置包,不能直接覆盖项目目录或作为完整编辑器数据包导入。 +文件夹模式递归读取 JSON,跳过非 JSON 文件和 `LevelInfoConfig.json`,按文件名中的数字排序。选择上一级 `levels` 时,批量结果 ZIP 保留 A、B 等子目录,避免同名文件覆盖。文件选择和文件夹选择以最后一次选择为准。建议使用 Chrome 或 Edge。 -## 选择文件夹批量转换 +可下载当前单关 JSON,或下载包含成功关卡及转换报告的批量 ZIP。失败关卡不会导出,不会压缩后续关卡编号。ZIP 不是完整编辑器数据包或项目配置包;解压后,在关卡编辑器的编排窗口中通过“从单关 JSON 导入”逐关新增,也可以通过“导入布局 JSON”替换当前布局。 -在“源关卡文件夹”选择 `D:\Downloads\piggy-jam-config\levels\A`,点击“转换”,完成后下载批量结果 ZIP。需要支持目录选择的浏览器,建议使用 Chrome 或 Edge。 +## 转换边界 -文件夹模式递归读取 JSON,跳过非 JSON 文件及 `LevelInfoConfig.json`,按文件名中的数字排序。也可选择上一级 `levels`:ZIP 中保留 A、B 等子目录,避免同名关卡覆盖。单个 JSON 的选择入口仍然保留,两种选择以最后一次选择为准。 +- 默认映射见下表,均属于 `animalGroup`;类型 `100` 在目标游戏中固定为 3 次碰撞。其他未知类型会阻止整关导出,不会跳过对象或替换成普通箭。 +- 坐标以 2 个源单位对应 1 个目标格转换,`size` 除以 2 得到棋盘列数和行数;`position` 是居中棋盘中的对象中心,Y 向上。目标左下角坐标为 `position / 2 + 目标棋盘尺寸 / 2 - 目标占格尺寸 / 2`。此规则已对照 level1 的目标布局,特殊类型仍需验收;不取整、不裁剪,无法对齐整数格时明确失败。 +- 默认角度 0° 向上、90° 向右,可调整零度朝向。导入后应对照原游戏检查坐标、占格、方向及玩法;转换通过不代表玩法等价。 +- 计时狮子映射为计时炸弹箭矢时支持 `boomTime`,其他未适配附加字段(路径、锁数量、泡泡等),以及云层、地鼠和非默认模式仍明确失败。 +- 相机、皮肤、奖励、关卡难度、主线顺序等不会自动迁移。输出仅含 `width`、`height`、`characters`、`aoes`,不会自动应用到项目。 -页面显示通过和未转换数量;未适配类型仍然会阻止对应关卡导出,详细原因见转换报告。选择文件夹不会修改源文件,也不会增加对特殊玩法的支持。 +## 默认映射 -## 合集转换规则 +| 源类型 | 源对象 | 目标对象 | 目标占格(沿朝向×侧向) | 对应的棋盘行为 | +| --- | --- | --- | --- | --- | +| 1 | 普通对象 | 箭(1) | 2×1 | 沿朝向移动 | +| 100 | 炸弹熊 | 爆破箭矢(2) | 2×1 | 碰撞3次爆炸 | +| 101 | 计时狮子 | 计时炸弹箭矢(4) | 2×1 | 倒计时爆炸 | +| 103 | 大象 | 张飞(5) | 3×2 | 大体型移动对象,战斗能力采用张飞配置 | +| 106 | 沉睡河马 | 张角(7) | 2×1 | 撞击后激活 | +| 107 | 魅力羊 | 黄忠(8) | 2×1 | 离场带动附近对象 | +| 108 | 撞击牛 | 赵云(9) | 2×1 | 可以撞破栅栏 | +| 109 | 羚羊 | 攻城车(10) | 2×1 | 碰撞后归位 | +| 112 | 小鸡 | 滚石(3) | 1×1 | 路径畅通时自动离场 | -- 支持 `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`。 +行为依据为源目录 `tables/LanguageConfig.json` 的中文说明,与本项目 `ArtifactConfig.json` 的棋盘行为对应;不代表跨项目的触发细节、战斗能力或关卡难度完全一致,仍需实机验收。撞击牛对应的源栅栏类型尚未适配,有相关障碍的关卡仍会拒绝导出。 -得到的文件在本项目编辑器中可用于“导入布局 JSON”替换当前布局,也可在“主线编排 → 新增方式 → 从单关 JSON 导入”新增关卡。模板提供场景、难度、敌人和关卡级配置。 +计时狮子(101)的非负数值 `boomTime` 转换为对象的 `addBuff` 中 `cool-down.buffParam.duration`,不修改源文件。若自定义映射已包含 `cool-down` 则明确报冲突;若改映射为其他军械,则不再消费 `boomTime`,仍提示未适配参数。源文件没有 `boomTime` 时不编造时间,沿用目标游戏默认规则。 -## 原始 Piggy Jam 转换边界 +目标模板的 `progression.boomTime` 优先于对象计时参数,时长达到180秒时还可能受目标难度上限限制。报告保留相关提醒,导入后必须核对最终倒计时,不能保证源时长原样应用。大象映射保留3×2占格,不代表源游戏具备张飞的战斗效果。 -- 默认将 `animalGroup.type=1` 转换为普通箭矢,`type=100` 转换为爆破箭矢(参考编排合集对同一源类型的爆破猪映射;目标固定 3 次碰撞,需验收玩法)。其他未知类型会阻止整关导出,不跳过对象,不降级为普通箭。 -- 当前坐标假设:`size` 是棋盘格数,`position` 是居中棋盘中的对象占格左下角,源坐标 Y 向上。坐标加半个棋盘尺寸得到目标锚点;不做取整、压缩或裁剪。此假设不是已确认的源游戏实现。 -- 默认 0° 向上,90° 向右;可以调整零度朝向。此规则尚未从原游戏代码或运行画面确认,必须先对照原游戏检查一个上下左右均有对象的关卡,不能将批量通过理解为玩法等价。 -- 映射规则中的 `length` 为沿朝向占格长度,`width` 为侧向宽度,必须与目标对象实际占格一致。工具不自带本项目完整对象目录,不能代替编辑器最终校验。 -- 原对象的炸弹时间、路径、锁数量等附加字段,以及云层、地鼠和非默认模式暂不支持;出现这些数据会明确失败。 -- 相机、皮肤不会进入目标文件。不会转换奖励、关卡难度、主线顺序等配置。 -- 输出仅包含 `width`、`height`、`characters`、`aoes`。不会自动应用到游戏项目。 +巡逻狼、动态尺寸笼子等还需路径或参数适配,暂不添加默认映射;其他不确定类型同样保留“未适配”提示。 ## 自定义映射 -页面“源类型与目标对象”列出已知近似关系,每种源类型下面可通过下拉框选择本项目的军械或机关,或设为“未适配 / 不转换”。选择后同步更新映射 JSON,必须重新转换,旧下载结果会失效。转换中发现的未知类型也会加入列表,不会自动分配替代对象。 +源分类仅有“动物(animalGroup)”和“机关(obstacleGroup)”。已知映射可通过目标对象下拉框修改,自动采用本项目对象的分类与占格。新增映射时填写非负整数源类型编号,同一分类不允许重复新增。 -通过“新增映射”选择源分类、填写源类型、选择目标对象。原始单关源类型填写数字(如 `112`),合集源类型填写名称(如 `wolf`);同一分类内不允许重复新增。每条关系可删除,删除前会确认。删除的只是转换规则,不会修改原文件或跳过源对象;再次遇到该类型会提示未适配,并重新列入待适配列表。映射仅保留在当前页面,重新打开会恢复默认;需保留自定义规则时保存映射 JSON,后续粘贴到高级编辑框。 +删除映射前会确认;删除的只是转换规则,不会删除或跳过源对象。遇到未知类型时提示“120 类型未适配”等信息,并加入待适配列表;完整错误和去重类型记录在报告的 `errors` 与 `unsupportedTypes` 中。 -下拉框自动使用目标对象的分类及占格,不会自动迁移源对象的炸弹、路径等特殊参数。选择替代类型不是玩法等价承诺;参数或占格不兼容时仍然失败。页面同时保留高级 JSON 编辑入口。 +修改映射后必须重新转换,旧下载结果会失效。映射仅保留在当前页面,重新打开恢复默认;需要复用时自行保留高级编辑框中的映射 JSON,下次粘贴使用。 -失败时结果上方单独提示“112 类型未适配”或“wolf 类型未适配”;报告的 `unsupportedTypes` 记录去重后的源分类和类型,完整错误仍保留在 `errors` 中。 +映射不会自动迁移特殊参数,选择目标对象也不保证行为等价。高级映射中的 `length` 为沿朝向长度,`width` 为侧向宽度,须与目标实际占格一致;`collection` 为 `characters` 或 `aoes`,`id` 为目标编号,可通过 `extra` 配置固定目标附加参数。最终仍需在本项目编辑器校验并实机验收。 -网页映射框可编辑,命令行可指定相同格式的 JSON 文件。键是源类型编号,`id` 是目标对象编号,`collection` 为 `characters` 或 `aoes`;可用 `extra` 配置固定目标附加参数。仅在确认源对象行为、大小和方向一致后添加映射。 +## 命令行 -## 批量输出 - -安装 Node.js 18 以上版本后运行(支持 Unicode 路径): +安装 Node.js 18 以上版本,运行: ```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 "D:\Downloads\文字挪车——前20关.json" "D:\Downloads\文字挪车-转换结果" -``` - -```powershell +node .\convert.mjs "D:\Downloads\piggy-jam-config\levels\A\level3.json" "D:\Downloads\level3-转换结果" node .\convert.mjs "输入目录" "新建输出目录" "自定义映射.json" north ``` + +输出目录必须尚不存在。命令行目录模式只读取该目录下的 `level数字.json`,不递归。成功文件逐个输出,失败文件不输出,详细原因写入 `转换报告.json`;部分失败时退出码为 2。零度朝向可选 `north`、`east`、`south`、`west`。 diff --git a/抓猪关卡转换/piggy-converter/转换工具.html b/抓猪关卡转换/piggy-converter/转换工具.html index 8386f16..d2b70e5 100644 --- a/抓猪关卡转换/piggy-converter/转换工具.html +++ b/抓猪关卡转换/piggy-converter/转换工具.html @@ -14,14 +14,14 @@

源类型与目标对象

- +

-

默认近似对应:pig → 箭、pigBomb → 爆破箭矢、pigClock → 计时炸弹箭矢、duck → 滚石、bear → 张飞。原始单关仅默认支持 1 → 箭、100 → 爆破箭矢;不能与合集类型混用。跨项目行为不保证等价。爆破箭矢固定 3 次碰撞,计时时长可能受模板和难度上限影响。选择替换类型不会自动适配源对象的特殊参数;占格或参数不兼容时仍会失败。

+

默认对应:1 → 箭、100 炸弹熊 → 爆破箭矢、101 计时狮子 → 计时炸弹箭矢、103 大象 → 张飞、106 沉睡河马 → 张角、107 魅力羊 → 黄忠、108 撞击牛 → 赵云、109 羚羊 → 攻城车、112 小鸡 → 滚石。爆破箭矢固定 3 次碰撞;大象对应张飞的 3×2 占格,战斗能力采用张飞配置。计时狮子的 boomTime 转为计时附加参数,但可能被目标模板和难度覆盖,须核对最终倒计时。其他特殊参数仍需单独适配;占格或参数不兼容时转换失败。

转换结果

未选择文件
@@ -30,20 +30,18 @@ const $=id=>document.getElementById(id);let results=[],generation=0,sourceFiles=[]; $('mapping').value=JSON.stringify(PiggyConverter.defaults,null,2); const discoveredTypes=new Map(); -const groupNames={animalGroup:'原始单关 · 动物',obstacleGroup:'原始单关 · 机关',animals:'合集 / 当前布局'}; +const groupNames={animalGroup:'动物',obstacleGroup:'机关'}; 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('合集源类型须以字母开头,仅含字母、数字、下划线或连字符'); + if(!/^(0|[1-9]\d*)$/.test(type)||!Number.isSafeInteger(Number(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)&¤t[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;} @@ -71,9 +69,6 @@ function renderMappings(){ 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(); @@ -123,12 +118,12 @@ $('convert').onclick=async()=>{ 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);} + let item;try{if(file.size>32*1024*1024)throw Error('文件不能超过 32MB');const text=await file.text();if(current!==generation)return;item=PiggyConverter.convert(JSON.parse(text.replace(/^\uFEFF/,'')),mapping,zero);}catch(error){item={ok:false,errors:['转换失败:'+error.message]};} + const folders=(file.webkitRelativePath||'').split('/').slice(1,-1).map(part=>PiggyConverter.outputName(part+'.json').slice(0,-5).replace(/^\.+$/,'_')); + converted.push({file:file.webkitRelativePath||file.name,output:[...folders,PiggyConverter.outputName(file.name)].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;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(); + if(current!==generation)return;results=converted;renderMappings();$('selected').replaceChildren(...results.map((item,index)=>new Option((item.ok?'通过 · ':'未转换 · ')+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 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);}