Files
nixingnishang_level-editor/抓猪关卡转换/piggy-converter/converter.cjs
T

152 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(function (root) {
'use strict';
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: [] };
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 = 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;
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('相机参数、皮肤编号、难度、奖励不导入;目标关卡级配置由编辑器所选模板继承。');
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 };
}
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);