conv_lvs.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. #!/usr/local/bin/python3
  2. # -*- coding: utf-8 -*-
  3. # File: conv_lvs.py
  4. # Desc: 将用到的关卡文件压缩成程序使用的protobuf格式
  5. # Date: 2017-04-18
  6. import os
  7. import sys
  8. import json
  9. import levelData_pb2
  10. import time
  11. def read_json(file_path):
  12. with open(file_path, 'r') as file:
  13. return json.load(file)
  14. def write_json(data, file_path):
  15. with open(file_path, 'w+') as file:
  16. json.dump(data, file, indent=4)
  17. # 将 ../conf/levelInstInfo.csv 里面的每一个实例的模板名加上“tf_”前缀
  18. def add_prefix_to_inst_name():
  19. with open('../conf/levelInstInfo.csv', 'r') as f:
  20. hdr_done = False
  21. with open('../conf/levelInstInfo_new.csv', 'w+') as f_new:
  22. for line in f.readlines():
  23. if line.startswith('#'):
  24. f_new.write(line)
  25. continue
  26. if not hdr_done:
  27. f_new.write(line)
  28. hdr_done = True
  29. continue
  30. line = line.split(',')
  31. if line[1].startswith('tf_'):
  32. f_new.write(line)
  33. continue
  34. line[1] = 'tf_' + line[1]
  35. f_new.write(','.join(line))
  36. # 解析 ../conf/levelInstInfo.csv 文件,得到所有被用到的模板列表
  37. def parse_level_inst_info(groups):
  38. temp_list = set()
  39. for grp in groups:
  40. fn = '../conf/levelInstInfo.csv'
  41. if len(grp) != 0:
  42. fn = '../conf/levelInstInfo-' + grp + '.csv'
  43. with open(fn, 'r') as f:
  44. # 跳过第一行
  45. f.readline()
  46. for line in f.readlines():
  47. if line.startswith('#'):
  48. continue
  49. temp_list.add(line.split(',')[1])
  50. return temp_list
  51. # 将某个tiled的json文件转换成protobuf格式
  52. def conver_json_to_proto(tDir, tFileName, outDir):
  53. global lvFileInfo, lvInfo
  54. jsonFile = os.path.join(tDir, tFileName + '.json')
  55. with open(jsonFile, 'r') as f:#, encoding='utf-8'
  56. jsonData = json.load(f)
  57. levelData = levelData_pb2.LevelData()
  58. levelData.tileWidth = jsonData['width']
  59. levelData.tileHeight = jsonData['height']
  60. cntUndefined = 0
  61. tilesByPos = {}
  62. maxZ = 0
  63. maxX = 0
  64. maxY = 0
  65. # 首先得到stacked的坐标数据
  66. stacked_map = {}
  67. for item in jsonData['layers']:
  68. name = item['name']
  69. if name == 'Marks':
  70. data = item['data']
  71. for i in range(0, len(data)):
  72. if data[i] == 0:
  73. continue
  74. x = (int)(i % levelData.tileWidth)
  75. y = (int)(i / (int)(levelData.tileWidth))
  76. stacked_map[(x, y)] = 0
  77. # 处理各层的tile数据
  78. cntTiles = 0
  79. for item in jsonData['layers']:
  80. name = item['name']
  81. if not name.startswith('Tile_'):
  82. # stacked
  83. continue
  84. z = int(name[5:])
  85. data = item['data']
  86. for i in range(0, len(data)):
  87. if data[i] == 0:
  88. continue
  89. tile = levelData.tiles.add()
  90. tile.x = (int)(i % levelData.tileWidth)
  91. tile.y = (int)(i / (int)(levelData.tileWidth))
  92. tile.z = z
  93. if (tile.x, tile.y) in stacked_map:
  94. stacked_map[(x, y)] += 1
  95. tiledata = tile.tileData
  96. tiledata.zv = 0
  97. tiledata.weight = 0
  98. tiledata.id = data[i]
  99. if tiledata.id == -10:
  100. cntUndefined += 1
  101. tiledata.type = 1
  102. tiledata.subtype = 0
  103. # 一些统计信息
  104. tilesByPos[(tile.x, tile.y, tile.z)] = tile
  105. if tile.z > maxZ:
  106. maxZ = tile.z
  107. if tile.x > maxX:
  108. maxX = tile.x
  109. if tile.y > maxY:
  110. maxY = tile.y
  111. cntTiles += 1
  112. print('Tile 总数: %d' % (cntTiles,))
  113. if cntTiles%3 != 0:
  114. print('Error: Tile总数不是3的倍数 3: %d' % (cntTiles,))
  115. exit(1)
  116. # 检查每层的tile是否有重叠
  117. pos_conflict = {}
  118. for z in range(0, maxZ+1):
  119. for x in range(0, maxX+1):
  120. for y in range(0, maxY+1):
  121. if (x,y,z) in tilesByPos:
  122. adjs = [(0,1),(0,-1),(1,0),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1)]
  123. for adj in adjs:
  124. p = (x+adj[0],y+adj[1],z)
  125. if p in tilesByPos:
  126. if (x,y) not in pos_conflict:
  127. pos_conflict[(x,y,z)] = []
  128. pos_conflict[(x,y,z)].append(p)
  129. for p,ps in pos_conflict.items():
  130. print("位置冲突:", p, ps)
  131. if len(pos_conflict) > 0:
  132. exit(1)
  133. time.sleep(3)
  134. # 根据上面的布局信息,计算每个tile的几个信息:
  135. # 1. 每个tile的视觉层级(不同于上面z的信息,那是一个布局信息,相同的z可能出在不同的视觉层级)
  136. # 从maxZ开始,逐层向下计算;对于每一个位置,如果该位置有tile,则计算该tile的视觉层级
  137. # 对于每一个tile,如果其上方(从该tile的z+1层,一直到maxZ层)有tile,则其视觉层级为上方tile的视觉层级+1
  138. for z in range(0, maxZ+1):
  139. z = maxZ - z
  140. for x in range(0, maxX+1):
  141. for y in range(0, maxY+1):
  142. if (x,y,z) in tilesByPos:
  143. tile = tilesByPos[(x, y, z)]
  144. adjs = [(x,y),(x,y+1),(x,y-1),(x+1,y),(x+1,y+1),(x+1,y-1),(x-1,y),(x-1,y-1),(x-1,y+1)]
  145. # 确定视觉层级
  146. zvMax = -1
  147. for zup in range(z+1, maxZ+1):
  148. for adj in adjs:
  149. if (adj[0],adj[1],zup) in tilesByPos:
  150. zv = tilesByPos[adj[0],adj[1],zup].tileData.zv
  151. if zv > zvMax:
  152. zvMax = zv
  153. tile.tileData.zv = zvMax + 1
  154. # 计算权重
  155. # 从最底下开始,逐层向上计算
  156. # 每个tile的初始权重为4,然后加上其下方压住的tile的权重:如果压了全部,则该加上被压住的tile权重;
  157. # 如果压住了一半,则加上被压住的tile权重的一半;如果是压住1/4,则加上被压住的tile权重的1/4
  158. for z in range(0, maxZ+1):
  159. for x in range(0, maxX+1):
  160. for y in range(0, maxY+1):
  161. if (x,y,z) in tilesByPos:
  162. tile = tilesByPos[(x,y,z)]
  163. adjs = [(x,y,1.0),(x,y+1,0.5),(x,y-1,0.5),(x+1,y,0.5),(x+1,y+1,0.25),(x+1,y-1,0.25),(x-1,y,0.5),(x-1,y-1,0.25),(x-1,y+1,0.25)]
  164. weight = 4
  165. for adj in adjs:
  166. # 从临近层往下,在某个位置找到了tile,则该tile被压住了,就不再找了
  167. for zb in range(0, z):
  168. zb = z-1-zb
  169. if (adj[0], adj[1], zb) in tilesByPos:
  170. tileB = tilesByPos[(adj[0], adj[1], zb)]
  171. weight += tileB.tileData.weight * adj[2]
  172. break
  173. tile.tileData.weight = int(weight)
  174. pass
  175. for item in stacked_map:
  176. stack_data = levelData.stacks.add()
  177. stack_data.x = int(item[0])
  178. stack_data.y = int(item[1])
  179. stack_data.direction = 0 # 先默认都是0
  180. # 数据序列化
  181. level_protobuf_data = levelData.SerializeToString()
  182. protoFile = os.path.join(outDir, tFileName + '.bin')
  183. with open(protoFile, 'w+b') as f:
  184. f.write(level_protobuf_data)
  185. def gen_index_and_data(binDir, group = None):
  186. lvelsIndex = levelData_pb2.LevelsIndex()
  187. if group is not None:
  188. protoDataTrunk = os.path.join(binDir, 'levels-' + str(group) + '.bin')
  189. protoDataIndex = os.path.join(binDir, 'levelsIndex-' + str(group) + '.bin')
  190. else:
  191. protoDataTrunk = os.path.join(binDir, 'levels' + '.bin')
  192. protoDataIndex = os.path.join(binDir, 'levelsIndex' + '.bin')
  193. offset = 0
  194. for filename in os.listdir(binDir):
  195. my_message = levelData_pb2.LevelData()
  196. binFile = os.path.splitext(filename)[0] + '.bin'
  197. binFile = os.path.join(binDir, binFile)
  198. if os.path.exists(binFile) :
  199. # print(binFile)
  200. with open(binFile, "rb") as f:
  201. binary_data = f.read()
  202. my_message.ParseFromString(binary_data)
  203. os.remove(binFile)
  204. with open(protoDataTrunk, 'ab') as f:
  205. f.write(binary_data)
  206. lvelsIndex.LevelsIndex[os.path.splitext(filename)[0]].len = len(binary_data)
  207. lvelsIndex.LevelsIndex[os.path.splitext(filename)[0]].offset = offset
  208. offset += len(binary_data)
  209. level_protobuf_index = lvelsIndex.SerializePartialToString()
  210. with open(protoDataIndex, 'w+b') as f:
  211. f.write(level_protobuf_index)
  212. # 将所有的模板文件转换成protobuf格式
  213. def convert_all_templates():
  214. # 清空loadable目录
  215. for root, dirs, files in os.walk('../loadable'):
  216. for name in files:
  217. os.remove(os.path.join(root, name))
  218. temp_list = parse_level_inst_info(['','3'])
  219. dirs = ['../tf_templates', '../miniGame', '../templates']
  220. for temp_name in temp_list:
  221. print(f"Converting template {temp_name}")
  222. # 判断正确的目录
  223. for d in dirs:
  224. if os.path.exists(os.path.join(d, temp_name + '.json')):
  225. conver_json_to_proto(d, temp_name, '../loadable')
  226. break
  227. gen_index_and_data('../loadable')
  228. # 修改levelInstInfo.csv文件: 对于每一行,如果其try1一直到try10的随机数都是100,则一次将其加1
  229. def correct_random_seed():
  230. for f in ['../conf/levelInstInfo.csv', '../conf/levelInstInfo-2.csv']:
  231. lines = None
  232. with open(f, 'r') as file:
  233. lines = file.readlines()
  234. with open(f, 'w') as file:
  235. for line in lines:
  236. if line.startswith('#'):
  237. file.write(line)
  238. continue
  239. fs = line.split(',')
  240. if len(fs) < 12:
  241. file.write(line)
  242. continue
  243. for i in range(2, 12):
  244. if fs[i].split('|')[1] == '100':
  245. fs[i] = fs[i].replace('100', '%d' % (100+i))
  246. file.write(','.join(fs))
  247. # 将关卡实例每个关卡单独保存一个,避免改动的时候相互影响
  248. def split_level_inst_info():
  249. # 首先读取levelInfo.csv文件,对于每一个关卡,解析其所使用的实例名字信息
  250. # 然后读取levelInstInfo.csv文件,得到每一个实例的详细信息
  251. # 新建一个levelInstInfo-new.csv文件,对于每一个关卡,将其所使用的实例的信息改名成inst-关卡名,并存入上一步的详细信息
  252. # 最后将levelInstInfo-new.csv文件保存
  253. lvs_inst = {}
  254. with open('../conf/levelInfo-2.csv', 'r') as file:
  255. for line in file.readlines():
  256. if line.startswith('#'):
  257. continue
  258. fs = line.split(',')
  259. lvs_inst[fs[0]] = (fs[1], fs)
  260. inst_info = {}
  261. with open('../conf/levelInstInfo-2.csv', 'r') as file:
  262. for line in file.readlines():
  263. if line.startswith('#'):
  264. continue
  265. fs = line.split(',')
  266. inst_info[fs[0]] = ",".join(fs[1:])
  267. # 更新info
  268. with open('../conf/levelInfo-2-new.csv', 'w') as file:
  269. for lv, (inst,li) in lvs_inst.items():
  270. li[1] = 'inst-%s' % (lv,)
  271. file.write(",".join(li))
  272. # 写入实例信息
  273. with open('../conf/levelInstInfo-2-new.csv', 'w') as file:
  274. for lv, (inst,li) in lvs_inst.items():
  275. if inst in inst_info:
  276. file.write("inst-%s,%s" % (lv, inst_info[inst]))
  277. else:
  278. print(f"Error: {inst} not found in levelInstInfo.csv")
  279. pass
  280. # 更新关卡实例的随机值
  281. def updateRandomSeed(lvInfoFN, instInfoFN, seedsInfo):
  282. # seedsInfo每一行的格式:[Tile] resovler id: 31,37710|539110|14697|465925|662106|151463|667120|234313|60714|840794|
  283. # 解析seedsInfo,得到关卡和实例的时机值
  284. seeds = {}
  285. for line in seedsInfo.split('\n'):
  286. fs = line.split(' ')
  287. if len(fs) < 4:
  288. continue
  289. fs = fs[3].split(',')
  290. seeds[fs[0]] = fs[1].split('|')
  291. # 先通过lvInfoFN文件,得到所有的关卡对应的实例名称
  292. seeds4Inst = {}
  293. with open(lvInfoFN, 'r') as file:
  294. for line in file.readlines():
  295. if line.startswith('#'):
  296. continue
  297. fs = line.split(',')
  298. if fs[0] in seeds:
  299. seeds4Inst[fs[1]] = seeds[fs[0]]
  300. # 对于instInfoFN文件,对于每一行,如果lvid在seeds里面,则用上面的随机值来更新一下;否则原封不动写入新文件
  301. with open(instInfoFN, 'r') as infile:
  302. lines = infile.readlines()
  303. with open(instInfoFN + '-new', 'w') as outfile:
  304. for line in lines:
  305. fs = line.split(',')
  306. if len(fs) < 2:
  307. outfile.write(line)
  308. continue
  309. if fs[0] in seeds4Inst:
  310. for i in range(2, 12):
  311. v = seeds4Inst[fs[0]][i-2].split('-')
  312. ps = fs[i].split('|')
  313. ps[0] = v[0]
  314. ps[1] = v[1]
  315. fs[i] = '|'.join(ps)
  316. outfile.write(','.join(fs))
  317. # 将instInfoFN-new文件重命名为instInfoFN
  318. os.rename(instInfoFN + '-new', instInfoFN)
  319. pass
  320. # 将所有的关卡文件中tile的尺寸调整一下
  321. def adjust_tile_size(templates_dir):
  322. # 遍历目录中的所有json文件,将属性 tileheight 和 tilewidth 调整为 40;
  323. # 将tilesets中所有元素的 imageheight 和 imagewidth 调整为 800, tilecount 调整为 100, tileheight 和 tilewidth 调整为 80
  324. for root, dirs, files in os.walk(templates_dir):
  325. for name in files:
  326. if not name.endswith('.json'):
  327. continue
  328. jsonFile = os.path.join(root, name)
  329. with open(jsonFile, 'r') as f:
  330. jsonData = json.load(f)
  331. jsonData['tilewidth'] = 40
  332. jsonData['tileheight'] = 40
  333. for tileset in jsonData['tilesets']:
  334. tileset['imageheight'] = 800
  335. tileset['imagewidth'] = 800
  336. tileset['tilecount'] = 100
  337. tileset['tileheight'] = 80
  338. tileset['tilewidth'] = 80
  339. with open(jsonFile, 'w') as f:
  340. json.dump(jsonData, f, indent=4)
  341. if __name__ == '__main__':
  342. # 获取当前工作目录
  343. current_dir = os.getcwd()
  344. script_dir = os.path.dirname(os.path.abspath(__file__))
  345. os.chdir(script_dir)
  346. # 得到可以发布的protobuf文件
  347. # convert_all_templates()
  348. # correct_random_seed()
  349. # split_level_inst_info()
  350. # 更新随机信息
  351. seedsInfo = """
  352. """
  353. #updateRandomSeed('../conf/levelInfo-3.csv', '../conf/levelInstInfo-3.csv', seedsInfo)
  354. adjust_tile_size("../tf_templates")
  355. # 恢复当前工作目录
  356. os.chdir(current_dir)