fileLoader.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. # print(allJson.keys())
  62. # print(filePath, filePath in allJson.keys())
  63. if filePath in allJson.keys():
  64. return allJson[filePath]
  65. elif filePath.lower() in allJson.keys():
  66. return allJson[filePath.lower()]
  67. else:
  68. # print(allJson.keys())
  69. if R.print_mode:
  70. print(f'打包文件内{filePath}不存在,读取单独文件')
  71. ...# print(f'打包文件内{filePath}不存在,读取单独文件')
  72. # print(allJson.keys())
  73. try:
  74. with open(filePath, 'r', encoding='utf-8') as f:
  75. data = json.load(f)
  76. except Exception as e:
  77. with open(filePath, 'r', encoding='utf-8_sig') as f:
  78. data = json.load(f)
  79. return data
  80. def load_rouge_data(filePath:str):
  81. # 首先尝试读取加密文件,如果没有则去真实路径读取
  82. import logging
  83. r_data = {}
  84. for root, dirs, files in os.walk(qqtpve_folder):
  85. for file in files:
  86. if file.endswith('.rougedata'):
  87. with open(os.path.join(root, file), 'rb') as f:
  88. try:
  89. r_data.update(decrypt_json(f.read()))
  90. # print(f'读取{file}...')
  91. except Exception as e:
  92. logging.error(f"读取{file}发生错误: {e}")
  93. ...#print(f'读取{file}失败')
  94. filePath = os.path.normpath(filePath)
  95. if filePath in r_data.keys():
  96. return r_data[filePath]
  97. elif filePath.lower() in r_data.keys():
  98. return r_data[filePath.lower()]
  99. else:
  100. ...# print(f'打包文件内{filePath}不存在,读取单独文件')
  101. try:
  102. with open(filePath, 'r', encoding='utf-8') as f:
  103. data = json.load(f)
  104. except Exception as e:
  105. print(e)
  106. try:
  107. with open(filePath, 'r', encoding='utf-8_sig') as f:
  108. data = json.load(f)
  109. except Exception as e:
  110. print(e)
  111. with open(filePath, 'r', encoding='latin-1') as f: # latin-1
  112. data = json.load(f)
  113. return data
  114. def save_encrypt_single_rouge_file(fileData, fileName:str):
  115. if not os.path.exists('game/rougeLocalData'):
  116. os.mkdir('game/rougeLocalData')
  117. data = {}
  118. # 加载文件内容到字典
  119. data[qqtpve_folder+"\\"+fileName+".rougedata"] = fileData
  120. # print(data)
  121. # 加密数据
  122. encrypted_data = encrypt_json(data)
  123. # 生成加密文件的名称
  124. encryptedFileName = f'{qqtpve_folder}/{fileName}.rougedata'
  125. localEncryptedFileName = f'game/rougeLocalData/{fileName}.rougedata'
  126. # 尝试删除已存在的文件
  127. '''
  128. for file_path in [encryptedFileName, localEncryptedFileName]:
  129. try:
  130. if os.path.exists(file_path):
  131. os.remove(file_path)
  132. except Exception as e:
  133. print(f"删除旧文件时发生错误:{e}")
  134. return None
  135. '''
  136. # 保存
  137. try:
  138. with open(encryptedFileName, 'wb') as f:
  139. f.write(encrypted_data)
  140. # print(f'肉鸽加密文件已保存为: {encryptedFileName}')
  141. except Exception as e:
  142. print(f"保存加密肉鸽文件时发生错误:{e}")
  143. return None
  144. try:
  145. with open(localEncryptedFileName, 'wb') as f:
  146. f.write(encrypted_data)
  147. # print(f'肉鸽加密文件已保存为: {localEncryptedFileName}')
  148. except Exception as e:
  149. print(f"保存加密肉鸽文件时发生错误:{e}")
  150. return None
  151. def encrypt_into_onefile():
  152. if not os.path.exists('gameFiles'):
  153. os.mkdir('gameFiles')
  154. data = {}
  155. for root, dirs, files in os.walk('./game'):
  156. for file in files:
  157. if file.endswith('.json'):
  158. with open(os.path.join(root, file), 'r', encoding='utf-8') as f:
  159. filePath = os.path.join(root, file)
  160. filePath = os.path.normpath(filePath).lower()
  161. data[filePath] = json.load(f)
  162. data = encrypt_json(data)
  163. with open('game.pveres', 'wb') as f:
  164. f.write(data)
  165. initOK = False
  166. allJson = {}
  167. def init():
  168. '''
  169. 读取gameFiles文件夹下的所有文件,解密并通过update保存到一个字典
  170. '''
  171. global initOK, allJson
  172. data = {}
  173. # '''
  174. for root, dirs, files in os.walk(qqtpve_folder):
  175. for file in files:
  176. if file.endswith('.rougedata'):
  177. with open(os.path.join(root, file), 'rb') as f:
  178. try:
  179. data.update(decrypt_json(f.read()))
  180. # print(f'读取{file}...')
  181. except:
  182. # print(f'读取{file}失败')
  183. ...#print(f'读取{file}失败')
  184. # '''
  185. if os.path.exists('game.pveres'):
  186. # print('读取默认游戏地图中...')
  187. with open('game.pveres', 'rb') as f:
  188. data.update(decrypt_json(f.read()))
  189. # else:
  190. # print(f"game.pveres 不存在")
  191. for root, dirs, files in os.walk('game/gameFiles'):
  192. for file in files:
  193. if file.endswith('.pveres'):
  194. # print(f"load file: {file}")
  195. with open(os.path.join(root, file), 'rb') as f:
  196. try:
  197. # os.path.normpath(filePath)
  198. data.update(decrypt_json(f.read()))
  199. # print(f'读取{file}...')
  200. except Exception as e:
  201. print(f'读取{file}失败, error: {e}')
  202. ...#print(f'读取{file}失败')
  203. allJson = data
  204. # print(allJson.keys())
  205. initOK = True
  206. def encrypt_imgs_into_oneFile():
  207. '''读取所有图片文件,根据路径生成字典,加密后保存到一个文件'''
  208. data = {}
  209. totalFileNum = 0
  210. for root, dirs, files in os.walk('./res'):
  211. for file in files:
  212. if file.endswith('.png'):
  213. totalFileNum += 1
  214. # print(f'共有{totalFileNum}个文件')
  215. i = 0
  216. for root, dirs, files in os.walk('./res'):
  217. for file in files:
  218. if file.endswith('.png'):
  219. filePath = os.path.join(root, file)
  220. filePath = os.path.normpath(filePath).lower()
  221. with open(filePath, 'rb') as f:
  222. data[filePath] = base64.b64encode(f.read()).decode('utf-8')
  223. if i%100 == 0:
  224. print(f'{i}/{totalFileNum} 读取{filePath}')
  225. i += 1
  226. data = encrypt_json(data)
  227. with open('game_imgs.pveimg', 'wb') as f:
  228. f.write(data)
  229. imgInitOK = False
  230. allImgs = {}
  231. def init_img():
  232. '''读取gameFiles文件夹下的所有文件,解密并通过update保存到一个字典'''
  233. import os
  234. data = {}
  235. global imgInitOK, allImgs
  236. if os.path.exists('game_imgs.pveimg'):
  237. print('读取默认游戏素材中...')
  238. with open('game_imgs.pveimg', 'rb') as f:
  239. data.update(decrypt_json(f.read()))
  240. for root, dirs, files in os.walk('game/gameFiles'):
  241. for file in files:
  242. if file.endswith('.pveimg'):
  243. # print(f'读取{file}...')
  244. with open(os.path.join(root, file), 'rb') as f:
  245. data.update(decrypt_json(f.read()))
  246. allImgs = data
  247. imgInitOK = True
  248. # with open('allImgs.json', 'w') as f:
  249. # json.dump(list(allImgs.keys()), f)
  250. # print(allImgs.keys()[0])
  251. def load_png(filePath:str):
  252. # 首先尝试读取加密文件,如果没有则去真实路径读取
  253. global imgInitOK, allImgs
  254. if not imgInitOK:
  255. init_img()
  256. #print(f'加载文件{filePath}')
  257. filePath = os.path.normpath(filePath)
  258. if filePath.lower() in allImgs.keys():
  259. dataB64 = allImgs[filePath.lower()]
  260. image_data = base64.b64decode(dataB64)
  261. # 使用Pillow打开图像
  262. pillow_image = Image.open(io.BytesIO(image_data))
  263. pillow_image = pillow_image.convert("RGBA")
  264. # 获取图像的大小
  265. width, height = pillow_image.size
  266. # 获取图像的原始数据
  267. image_data = np.array(pillow_image)
  268. image_surface = pygame.image.fromstring(image_data.tobytes(), (width, height), 'RGBA').convert_alpha() # 不进行转换会降低效率(?为啥呢)
  269. return image_surface
  270. elif filePath in allImgs.keys():
  271. dataB64 = allImgs[filePath]
  272. image_data = base64.b64decode(dataB64)
  273. # 使用Pillow打开图像
  274. pillow_image = Image.open(io.BytesIO(image_data))
  275. pillow_image = pillow_image.convert("RGBA")
  276. # 获取图像的大小
  277. width, height = pillow_image.size
  278. # 获取图像的原始数据
  279. image_data = np.array(pillow_image)
  280. image_surface = pygame.image.fromstring(image_data.tobytes(), (width, height), 'RGBA').convert_alpha() # 不进行转换会降低效率(?为啥呢)
  281. return image_surface
  282. else:
  283. ...#print(f'打包文件内{filePath}不存在,读取单独文件')
  284. # 没有png文件,返回空
  285. if filePath.endswith('.png') and not os.path.exists(filePath):
  286. #print(filePath, '不存在')
  287. text = '[X]'
  288. font = pygame.font.SysFont('arial', 40)
  289. image_surface = font.render(text, True, (255, 0, 0))
  290. # image_surface = pygame.Surface((40, 40)).convert_alpha()
  291. # image_surface.fill((255, 0, 0))
  292. # print("没找到图片哇:", filePath)
  293. return image_surface
  294. #print(filePath, '读取')
  295. return pygame.image.load(filePath).convert_alpha()
  296. from PIL import Image, ImageTk
  297. import tkinter
  298. def load_png_pillow(filePath:str):
  299. # 首先尝试用json读取,如果失败则尝试用加密方式读取
  300. global imgInitOK, allImgs
  301. if not imgInitOK:
  302. init_img()
  303. #print(f'加载文件{filePath}')
  304. filePath = os.path.normpath(filePath)
  305. if filePath in allImgs.keys():
  306. dataB64 = allImgs[filePath]
  307. image_data = base64.b64decode(dataB64)
  308. # 使用Pillow打开图像
  309. pillow_image = Image.open(io.BytesIO(image_data))
  310. return pillow_image
  311. elif filePath.lower() in allImgs.keys():
  312. dataB64 = allImgs[filePath.lower()]
  313. image_data = base64.b64decode(dataB64)
  314. # 使用Pillow打开图像
  315. pillow_image = Image.open(io.BytesIO(image_data))
  316. return pillow_image
  317. else:
  318. ...#print(f'打包文件内{filePath}不存在,读取单独文件')
  319. # 没有png文件,返回空
  320. if filePath.endswith('.png') and not os.path.exists(filePath):
  321. return
  322. #print(filePath)
  323. return Image.open(filePath)
  324. if __name__=='__main__':
  325. #allJson = init()
  326. #print(allJson)
  327. encrypt_into_onefile()
  328. #init()
  329. encrypt_imgs_into_oneFile()