fileLoader.py 13 KB

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