conv_tilefamily.py 2.1 KB

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