using System.Collections.Generic; using System.IO; using UnityEngine; namespace EditorTools { // 导出JSON 根实体 [System.Serializable] public class ExportLevelRoot { public int levelId; public string levelName; public int gridRows; public int gridCols; public int pointSpacing; public List arrows; } // 导出JSON 单条箭头实体 [System.Serializable] public class ExportArrowItem { public int id; public int startPoint; public int endPoint; public string color; public List path; } public static class LevelJsonExporter { /// /// 行列转点位ID(和游戏代码完全一致) /// public static int RowColToPointId(int row, int col, int totalCol) { return row * totalCol + col; } /// /// 点位ID转行列(和游戏代码完全一致) /// public static void PointIdToRowCol(int pointId, int totalCol, out int row, out int col) { row = pointId / totalCol; col = pointId % totalCol; } /// /// 根据前后两个点位,计算移动方向 /// public static string GetDirection(int fromId, int toId, int totalCol) { PointIdToRowCol(fromId, totalCol, out int fRow, out int fCol); PointIdToRowCol(toId, totalCol, out int tRow, out int tCol); if (tRow < fRow) return "up"; if (tRow > fRow) return "down"; if (tCol < fCol) return "left"; if (tCol > fCol) return "right"; return ""; } /// /// 生成最终JSON字符串(纯实体类序列化,全版本兼容) /// public static string BuildLevelJson(EditorLevelData levelData) { ExportLevelRoot root = new ExportLevelRoot(); root.levelId = levelData.levelId; root.levelName = levelData.levelName; root.gridRows = levelData.gridRows; root.gridCols = levelData.gridCols; root.pointSpacing = levelData.pointSpacing; root.arrows = new List(); foreach (var editorArr in levelData.arrows) { ExportArrowItem item = new ExportArrowItem(); item.id = editorArr.arrowId; item.startPoint = editorArr.startPoint; item.endPoint = editorArr.endPoint; item.color = editorArr.colorHex; item.path = new List(editorArr.pathDirs); root.arrows.Add(item); } return JsonUtility.ToJson(root, prettyPrint: true); } /// /// 保存JSON到StreamingAssets /// public static bool SaveToStreamingAssets(string json, string fileName = "level_1001.json") { string folder = Application.streamingAssetsPath; if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); string fullPath = Path.Combine(folder, fileName); File.WriteAllText(fullPath, json); Debug.Log($"[导出成功] {fullPath}"); return true; } } }