conv_tilefamily.py 2.0 KB

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