conv_tilefamily.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import json
  2. import os
  3. import copy
  4. def read_json(file_path):
  5. with open(file_path, 'r') as file:
  6. return json.load(file)
  7. def set_gid_in_layer(layer, x, y, gid):
  8. width = layer['width']
  9. index = (y+2) * width + x
  10. if index < len(layer['data']):
  11. layer['data'][index] = gid
  12. def update_tiled_json(file_name, source_json, tiled_template):
  13. for item in source_json['LevelData']:
  14. x, y, z = item['X'], item['Y'], item['Z']
  15. layer_name = f"Tile_{z}"
  16. if z > 16:
  17. print(f"Z{file_name} value too high: {z}")
  18. layer = next((l for l in tiled_template['layers'] if l['name'] == layer_name), None)
  19. if layer:
  20. set_gid_in_layer(layer, x, y, 1)
  21. else:
  22. print(f"Layer {layer_name} not found")
  23. marks_layer = next((l for l in tiled_template['layers'] if l['name'] == "Marks"), None)
  24. if marks_layer:
  25. for item in source_json['StackData']:
  26. x, y = item['X'], item['Y']
  27. set_gid_in_layer(marks_layer, x, y, 100)
  28. return tiled_template
  29. def write_json(data, file_path):
  30. with open(file_path, 'w+') as file:
  31. json.dump(data, file, indent=4)
  32. def process_files(source_dir, target_dir, template_file):
  33. tiled_template = read_json(template_file)
  34. for file_name in os.listdir(source_dir):
  35. if file_name.endswith('.json'):
  36. template = copy.deepcopy(tiled_template)
  37. source_file = os.path.join(source_dir, file_name)
  38. source_data = read_json(source_file)
  39. updated_tiled_data = update_tiled_json(file_name, source_data, template)
  40. base_name = os.path.splitext(file_name)[0]
  41. output_file = os.path.join(target_dir, f"tf_{base_name}.json")
  42. write_json(updated_tiled_data, output_file)
  43. # 获取当前工作目录
  44. current_dir = os.getcwd()
  45. script_dir = os.path.dirname(os.path.abspath(__file__))
  46. os.chdir(script_dir)
  47. # Example usage
  48. source_dir = '/Users/xulianxin/Documents/develop/game/TileMatch/TileManor.Lv/TileFamily/level_data2'
  49. target_dir = '../tf_templates'
  50. template_file = './0000-template.json'
  51. process_files(source_dir, target_dir, template_file)
  52. os.chdir(current_dir)