fileLoader.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. import zlib
  2. import json
  3. import base64
  4. import random
  5. import os
  6. import pygame
  7. import numpy as np
  8. import io
  9. import game.const.rouge as R
  10. from PIL import Image
  11. user_documents_folder = os.path.expanduser("~\\Documents") # 获取用户的"文档"文件夹路径
  12. qqtpve_folder = os.path.join(user_documents_folder, "QQTPVE") # 构建QQTPVE文件夹路径
  13. os.makedirs(qqtpve_folder, exist_ok=True) # 确保QQTPVE文件夹存在,如果不存在则创建
  14. MAX_ENCRYPT_LENGTH = 2000
  15. ENCRYPT_LENGTH_BYTES = MAX_ENCRYPT_LENGTH.to_bytes(4, 'little')
  16. def encrypt_json(data, KEY = 0x20220420):
  17. zlibBytes = zlib.compress(json.dumps(data).encode('utf-8'))
  18. fileLength = len(zlibBytes)
  19. header = b'QQTPVE FILE\x00\x00\x00\x00\x00' # 16字节
  20. fileLength_bytes = fileLength.to_bytes(4, 'little')
  21. #print(fileLength, fileLength_bytes)
  22. # 将zlibbytes与key_bytes异或
  23. zlibBytes = bytearray(zlibBytes)
  24. key_bytes = KEY.to_bytes(4, 'little')
  25. for i in range(min(fileLength, MAX_ENCRYPT_LENGTH)):
  26. zlibBytes[i] ^= key_bytes[i % 4]
  27. # 尾部随便增加一些字节,防止解密时越界
  28. for i in range(random.randint(0, 100)):
  29. zlibBytes += random.randint(0, 100).to_bytes(1, 'little')
  30. finByets = header + fileLength_bytes + ENCRYPT_LENGTH_BYTES + zlibBytes
  31. #print(finByets[:24])
  32. return finByets
  33. def decrypt_json(data, KEY = 0x20220420):
  34. header = data[:16]
  35. key_bytes = KEY.to_bytes(4, 'little')
  36. fileLength_bytes = data[16:20]
  37. fileLength = int.from_bytes(fileLength_bytes, 'little')
  38. entryptLength_bytes = data[20:24]
  39. entryptLength = int.from_bytes(entryptLength_bytes, 'little')
  40. #print(entryptLength_bytes,entryptLength)
  41. zlibBytes = data[24:24 + fileLength]
  42. #print(header,fileLength, fileLength_bytes)
  43. # 将zlibbytes与key_bytes异或
  44. zlibBytes = bytearray(zlibBytes)
  45. for i in range(min(fileLength,entryptLength)):
  46. zlibBytes[i] ^= key_bytes[i % 4]
  47. zlibBytes = zlibBytes[:fileLength]
  48. # print(zlibBytes)
  49. decompressed_data = zlib.decompress(zlibBytes)
  50. json_data = json.loads(decompressed_data.decode('utf-8'))
  51. # print(json_data)
  52. return json_data
  53. def load_json(filePath:str):
  54. # 首先尝试读取加密文件,如果没有则去真实路径读取
  55. global initOK
  56. if not initOK:
  57. init()
  58. # print(filePath, allJson.keys())
  59. # print(f'加载文件{filePath}')
  60. filePath = os.path.normpath(filePath)
  61. if filePath in allJson.keys():
  62. return allJson[filePath]
  63. elif filePath.lower() in allJson.keys():
  64. return allJson[filePath.lower()]
  65. else:
  66. # print(allJson.keys())
  67. if R.print_mode:
  68. print(f'打包文件内{filePath}不存在,读取单独文件')
  69. ...# print(f'打包文件内{filePath}不存在,读取单独文件')
  70. # print(allJson.keys())
  71. try:
  72. with open(filePath, 'r', encoding='utf-8') as f:
  73. data = json.load(f)
  74. except Exception as e:
  75. with open(filePath, 'r', encoding='utf-8_sig') as f:
  76. data = json.load(f)
  77. return data
  78. def load_rouge_data(filePath:str):
  79. # 首先尝试读取加密文件,如果没有则去真实路径读取
  80. import logging
  81. r_data = {}
  82. for root, dirs, files in os.walk(qqtpve_folder):
  83. for file in files:
  84. if file.endswith('.rougedata'):
  85. with open(os.path.join(root, file), 'rb') as f:
  86. try:
  87. r_data.update(decrypt_json(f.read()))
  88. # print(f'读取{file}...')
  89. except Exception as e:
  90. logging.error(f"读取{file}发生错误: {e}")
  91. ...#print(f'读取{file}失败')
  92. filePath = os.path.normpath(filePath)
  93. if filePath in r_data.keys():
  94. return r_data[filePath]
  95. elif filePath.lower() in r_data.keys():
  96. return r_data[filePath.lower()]
  97. else:
  98. ...# print(f'打包文件内{filePath}不存在,读取单独文件')
  99. try:
  100. with open(filePath, 'r', encoding='utf-8') as f:
  101. data = json.load(f)
  102. except:
  103. with open(filePath, 'r', encoding='utf-8_sig') as f:
  104. data = json.load(f)
  105. return data
  106. def save_encrypt_single_rouge_file(fileData, fileName:str):
  107. if not os.path.exists('game/rougeLocalData'):
  108. os.mkdir('game/rougeLocalData')
  109. data = {}
  110. # 加载文件内容到字典
  111. data[qqtpve_folder+"\\"+fileName+".rougedata"] = fileData
  112. # print(data)
  113. # 加密数据
  114. encrypted_data = encrypt_json(data)
  115. # 生成加密文件的名称
  116. encryptedFileName = f'{qqtpve_folder}/{fileName}.rougedata'
  117. localEncryptedFileName = f'game/rougeLocalData/{fileName}.rougedata'
  118. # 尝试删除已存在的文件
  119. '''
  120. for file_path in [encryptedFileName, localEncryptedFileName]:
  121. try:
  122. if os.path.exists(file_path):
  123. os.remove(file_path)
  124. except Exception as e:
  125. print(f"删除旧文件时发生错误:{e}")
  126. return None
  127. '''
  128. # 保存
  129. try:
  130. with open(encryptedFileName, 'wb') as f:
  131. f.write(encrypted_data)
  132. # print(f'肉鸽加密文件已保存为: {encryptedFileName}')
  133. except Exception as e:
  134. print(f"保存加密肉鸽文件时发生错误:{e}")
  135. return None
  136. try:
  137. with open(localEncryptedFileName, 'wb') as f:
  138. f.write(encrypted_data)
  139. # print(f'肉鸽加密文件已保存为: {localEncryptedFileName}')
  140. except Exception as e:
  141. print(f"保存加密肉鸽文件时发生错误:{e}")
  142. return None
  143. def encrypt_into_onefile():
  144. if not os.path.exists('gameFiles'):
  145. os.mkdir('gameFiles')
  146. data = {}
  147. for root, dirs, files in os.walk('./game'):
  148. for file in files:
  149. if file.endswith('.json'):
  150. with open(os.path.join(root, file), 'r', encoding='utf-8') as f:
  151. filePath = os.path.join(root, file)
  152. filePath = os.path.normpath(filePath).lower()
  153. data[filePath] = json.load(f)
  154. data = encrypt_json(data)
  155. with open('game.pveres', 'wb') as f:
  156. f.write(data)
  157. initOK = False
  158. allJson = {}
  159. def init():
  160. '''
  161. 读取gameFiles文件夹下的所有文件,解密并通过update保存到一个字典
  162. '''
  163. data = {}
  164. '''
  165. for root, dirs, files in os.walk(qqtpve_folder):
  166. for file in files:
  167. if file.endswith('.rougedata'):
  168. with open(os.path.join(root, file), 'rb') as f:
  169. try:
  170. data.update(decrypt_json(f.read()))
  171. # print(f'读取{file}...')
  172. except:
  173. # print(f'读取{file}失败')
  174. ...#print(f'读取{file}失败')
  175. '''
  176. if os.path.exists('game.pveres'):
  177. # print('读取默认游戏地图中...')
  178. with open('game.pveres', 'rb') as f:
  179. data.update(decrypt_json(f.read()))
  180. # else:
  181. # print(f"game.pveres 不存在")
  182. for root, dirs, files in os.walk('game/gameFiles'):
  183. for file in files:
  184. if file.endswith('.pveres'):
  185. with open(os.path.join(root, file), 'rb') as f:
  186. try:
  187. data.update(decrypt_json(f.read()))
  188. # print(f'读取{file}...')
  189. except:
  190. # print(f'读取{file}失败')
  191. ...#print(f'读取{file}失败')
  192. global initOK, allJson
  193. allJson = data
  194. initOK = True
  195. def encrypt_imgs_into_oneFile():
  196. '''读取所有图片文件,根据路径生成字典,加密后保存到一个文件'''
  197. data = {}
  198. totalFileNum = 0
  199. for root, dirs, files in os.walk('./res'):
  200. for file in files:
  201. if file.endswith('.png'):
  202. totalFileNum += 1
  203. # print(f'共有{totalFileNum}个文件')
  204. i = 0
  205. for root, dirs, files in os.walk('./res'):
  206. for file in files:
  207. if file.endswith('.png'):
  208. filePath = os.path.join(root, file)
  209. filePath = os.path.normpath(filePath).lower()
  210. with open(filePath, 'rb') as f:
  211. data[filePath] = base64.b64encode(f.read()).decode('utf-8')
  212. if i%100 == 0:
  213. print(f'{i}/{totalFileNum} 读取{filePath}')
  214. i += 1
  215. data = encrypt_json(data)
  216. with open('game_imgs.pveimg', 'wb') as f:
  217. f.write(data)
  218. imgInitOK = False
  219. allImgs = {}
  220. def init_img():
  221. '''读取gameFiles文件夹下的所有文件,解密并通过update保存到一个字典'''
  222. import os
  223. data = {}
  224. global imgInitOK, allImgs
  225. if os.path.exists('game_imgs.pveimg'):
  226. print('读取默认游戏素材中...')
  227. with open('game_imgs.pveimg', 'rb') as f:
  228. data.update(decrypt_json(f.read()))
  229. for root, dirs, files in os.walk('game/gameFiles'):
  230. for file in files:
  231. if file.endswith('.pveimg'):
  232. # print(f'读取{file}...')
  233. with open(os.path.join(root, file), 'rb') as f:
  234. data.update(decrypt_json(f.read()))
  235. allImgs = data
  236. imgInitOK = True
  237. # with open('allImgs.json', 'w') as f:
  238. # json.dump(list(allImgs.keys()), f)
  239. # print(allImgs.keys()[0])
  240. def load_png(filePath:str):
  241. # 首先尝试读取加密文件,如果没有则去真实路径读取
  242. global imgInitOK, allImgs
  243. if not imgInitOK:
  244. init_img()
  245. #print(f'加载文件{filePath}')
  246. filePath = os.path.normpath(filePath)
  247. if filePath.lower() in allImgs.keys():
  248. dataB64 = allImgs[filePath.lower()]
  249. image_data = base64.b64decode(dataB64)
  250. # 使用Pillow打开图像
  251. pillow_image = Image.open(io.BytesIO(image_data))
  252. pillow_image = pillow_image.convert("RGBA")
  253. # 获取图像的大小
  254. width, height = pillow_image.size
  255. # 获取图像的原始数据
  256. image_data = np.array(pillow_image)
  257. image_surface = pygame.image.fromstring(image_data.tobytes(), (width, height), 'RGBA').convert_alpha() # 不进行转换会降低效率(?为啥呢)
  258. return image_surface
  259. elif filePath in allImgs.keys():
  260. dataB64 = allImgs[filePath]
  261. image_data = base64.b64decode(dataB64)
  262. # 使用Pillow打开图像
  263. pillow_image = Image.open(io.BytesIO(image_data))
  264. pillow_image = pillow_image.convert("RGBA")
  265. # 获取图像的大小
  266. width, height = pillow_image.size
  267. # 获取图像的原始数据
  268. image_data = np.array(pillow_image)
  269. image_surface = pygame.image.fromstring(image_data.tobytes(), (width, height), 'RGBA').convert_alpha() # 不进行转换会降低效率(?为啥呢)
  270. return image_surface
  271. else:
  272. ...#print(f'打包文件内{filePath}不存在,读取单独文件')
  273. # 没有png文件,返回空
  274. if filePath.endswith('.png') and not os.path.exists(filePath):
  275. #print(filePath, '不存在')
  276. text = '[X]'
  277. font = pygame.font.SysFont('arial', 40)
  278. image_surface = font.render(text, True, (255, 0, 0))
  279. # image_surface = pygame.Surface((40, 40)).convert_alpha()
  280. # image_surface.fill((255, 0, 0))
  281. # print("没找到图片哇:", filePath)
  282. return image_surface
  283. #print(filePath, '读取')
  284. return pygame.image.load(filePath).convert_alpha()
  285. from PIL import Image, ImageTk
  286. import tkinter
  287. def load_png_pillow(filePath:str):
  288. # 首先尝试用json读取,如果失败则尝试用加密方式读取
  289. global imgInitOK, allImgs
  290. if not imgInitOK:
  291. init_img()
  292. #print(f'加载文件{filePath}')
  293. filePath = os.path.normpath(filePath)
  294. if filePath in allImgs.keys():
  295. dataB64 = allImgs[filePath]
  296. image_data = base64.b64decode(dataB64)
  297. # 使用Pillow打开图像
  298. pillow_image = Image.open(io.BytesIO(image_data))
  299. return pillow_image
  300. elif filePath.lower() in allImgs.keys():
  301. dataB64 = allImgs[filePath.lower()]
  302. image_data = base64.b64decode(dataB64)
  303. # 使用Pillow打开图像
  304. pillow_image = Image.open(io.BytesIO(image_data))
  305. return pillow_image
  306. else:
  307. ...#print(f'打包文件内{filePath}不存在,读取单独文件')
  308. # 没有png文件,返回空
  309. if filePath.endswith('.png') and not os.path.exists(filePath):
  310. return
  311. #print(filePath)
  312. return Image.open(filePath)
  313. if __name__=='__main__':
  314. #allJson = init()
  315. #print(allJson)
  316. encrypt_into_onefile()
  317. #init()
  318. encrypt_imgs_into_oneFile()