fileLoader.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import zlib
  2. import json
  3. import base64
  4. import random
  5. import os
  6. MAX_ENCRYPT_LENGTH = 2000
  7. ENCRYPT_LENGTH_BYTES = MAX_ENCRYPT_LENGTH.to_bytes(4, 'little')
  8. def encrypt_json(data, KEY = 0x20220420):
  9. zlibBytes = zlib.compress(json.dumps(data).encode('utf-8'))
  10. fileLength = len(zlibBytes)
  11. header = b'QQTPVE FILE\x00\x00\x00\x00\x00' # 16字节
  12. fileLength_bytes = fileLength.to_bytes(4, 'little')
  13. #print(fileLength, fileLength_bytes)
  14. # 将zlibbytes与key_bytes异或
  15. zlibBytes = bytearray(zlibBytes)
  16. key_bytes = KEY.to_bytes(4, 'little')
  17. for i in range(min(fileLength, MAX_ENCRYPT_LENGTH)):
  18. zlibBytes[i] ^= key_bytes[i % 4]
  19. # 尾部随便增加一些字节,防止解密时越界
  20. for i in range(random.randint(0, 100)):
  21. zlibBytes += random.randint(0, 100).to_bytes(1, 'little')
  22. finByets = header + fileLength_bytes + ENCRYPT_LENGTH_BYTES + zlibBytes
  23. #print(finByets[:24])
  24. return finByets
  25. def decrypt_json(data, KEY = 0x20220420):
  26. header = data[:16]
  27. key_bytes = KEY.to_bytes(4, 'little')
  28. fileLength_bytes = data[16:20]
  29. fileLength = int.from_bytes(fileLength_bytes, 'little')
  30. entryptLength_bytes = data[20:24]
  31. entryptLength = int.from_bytes(entryptLength_bytes, 'little')
  32. #print(entryptLength_bytes,entryptLength)
  33. zlibBytes = data[24:24 + fileLength]
  34. #print(header,fileLength, fileLength_bytes)
  35. # 将zlibbytes与key_bytes异或
  36. zlibBytes = bytearray(zlibBytes)
  37. for i in range(min(fileLength,entryptLength)):
  38. zlibBytes[i] ^= key_bytes[i % 4]
  39. zlibBytes = zlibBytes[:fileLength]
  40. # print(zlibBytes)
  41. decompressed_data = zlib.decompress(zlibBytes)
  42. json_data = json.loads(decompressed_data.decode('utf-8'))
  43. # print(json_data)
  44. return json_data
  45. def load_json(filePath:str):
  46. # 首先尝试读取加密文件,如果没有则去真实路径读取
  47. global initOK
  48. if not initOK:
  49. init()
  50. # print(f'加载文件{filePath}')
  51. filePath = os.path.normpath(filePath)
  52. if filePath in allJson.keys():
  53. return allJson[filePath]
  54. elif filePath.lower() in allJson.keys():
  55. return allJson[filePath.lower()]
  56. else:
  57. ...# print(f'打包文件内{filePath}不存在,读取单独文件')
  58. # print(filePath)
  59. if os.path.exists(filePath) and filePath !='.':
  60. try:
  61. with open(filePath, 'r', encoding='utf-8') as f:
  62. data:dict = json.load(f)
  63. except:
  64. with open(filePath, 'r', encoding='utf-8_sig') as f:
  65. data:dict = json.load(f)
  66. else:
  67. data = {}
  68. return data
  69. def encrypt_into_onefile():
  70. import os
  71. if not os.path.exists('gameFiles'):
  72. os.mkdir('gameFiles')
  73. data = {}
  74. for root, dirs, files in os.walk('./game'):
  75. for file in files:
  76. if file.endswith('.json'):
  77. with open(os.path.join(root, file), 'r', encoding='utf-8') as f:
  78. filePath = os.path.join(root, file)
  79. filePath = os.path.normpath(filePath).lower()
  80. data[filePath] = json.load(f)
  81. data = encrypt_json(data)
  82. with open('game.pveres', 'wb') as f:
  83. f.write(data)
  84. initOK = False
  85. allJson = {}
  86. def init():
  87. '''读取gameFiles文件夹下的所有文件,解密并通过update保存到一个字典'''
  88. import os
  89. data = {}
  90. if os.path.exists('game.pveres'):
  91. print('读取默认游戏地图中...')
  92. with open('game.pveres', 'rb') as f:
  93. data.update(decrypt_json(f.read()))
  94. for root, dirs, files in os.walk('game/gameFiles'):
  95. for file in files:
  96. if file.endswith('.pveres'):
  97. with open(os.path.join(root, file), 'rb') as f:
  98. try:
  99. data.update(decrypt_json(f.read()))
  100. # print(f'读取{file}...')
  101. except:
  102. # print(f'读取{file}失败')
  103. ...#print(f'读取{file}失败')
  104. global initOK, allJson
  105. allJson = data
  106. initOK = True
  107. # with open('allFiles.json', 'w') as f:
  108. # json.dump(list(allJson.keys()), f)
  109. import base64
  110. def encrypt_imgs_into_oneFile():
  111. '''读取所有图片文件,根据路径生成字典,加密后保存到一个文件'''
  112. data = {}
  113. totalFileNum = 0
  114. for root, dirs, files in os.walk('./res'):
  115. for file in files:
  116. if file.endswith('.png'):
  117. totalFileNum += 1
  118. # print(f'共有{totalFileNum}个文件')
  119. i = 0
  120. for root, dirs, files in os.walk('./res'):
  121. for file in files:
  122. if file.endswith('.png'):
  123. filePath = os.path.join(root, file)
  124. filePath = os.path.normpath(filePath).lower()
  125. with open(filePath, 'rb') as f:
  126. data[filePath] = base64.b64encode(f.read()).decode('utf-8')
  127. if i%100 == 0:
  128. print(f'{i}/{totalFileNum} 读取{filePath}')
  129. i += 1
  130. data = encrypt_json(data)
  131. with open('game_imgs.pveimg', 'wb') as f:
  132. f.write(data)
  133. imgInitOK = False
  134. allImgs = {}
  135. def init_img():
  136. '''读取gameFiles文件夹下的所有文件,解密并通过update保存到一个字典'''
  137. import os
  138. data = {}
  139. global imgInitOK, allImgs
  140. if os.path.exists('game_imgs.pveimg'):
  141. print('读取默认游戏素材中...')
  142. with open('game_imgs.pveimg', 'rb') as f:
  143. data.update(decrypt_json(f.read()))
  144. for root, dirs, files in os.walk('game/gameFiles'):
  145. for file in files:
  146. if file.endswith('.pveimg'):
  147. # print(f'读取{file}...')
  148. with open(os.path.join(root, file), 'rb') as f:
  149. data.update(decrypt_json(f.read()))
  150. allImgs = data
  151. imgInitOK = True
  152. # with open('allImgs.json', 'w') as f:
  153. # json.dump(list(allImgs.keys()), f)
  154. # print(allImgs.keys()[0])
  155. import pygame
  156. import numpy as np
  157. from PIL import Image
  158. import io
  159. def load_png(filePath:str):
  160. # 首先尝试读取加密文件,如果没有则去真实路径读取
  161. global imgInitOK, allImgs
  162. if not imgInitOK:
  163. init_img()
  164. #print(f'加载文件{filePath}')
  165. filePath = os.path.normpath(filePath)
  166. if filePath.lower() in allImgs.keys():
  167. dataB64 = allImgs[filePath.lower()]
  168. image_data = base64.b64decode(dataB64)
  169. # 使用Pillow打开图像
  170. pillow_image = Image.open(io.BytesIO(image_data))
  171. pillow_image = pillow_image.convert("RGBA")
  172. # 获取图像的大小
  173. width, height = pillow_image.size
  174. # 获取图像的原始数据
  175. image_data = np.array(pillow_image)
  176. image_surface = pygame.image.fromstring(image_data.tobytes(), (width, height), 'RGBA').convert_alpha() # 不进行转换会降低效率(?为啥呢)
  177. return image_surface
  178. elif filePath in allImgs.keys():
  179. dataB64 = allImgs[filePath]
  180. image_data = base64.b64decode(dataB64)
  181. # 使用Pillow打开图像
  182. pillow_image = Image.open(io.BytesIO(image_data))
  183. pillow_image = pillow_image.convert("RGBA")
  184. # 获取图像的大小
  185. width, height = pillow_image.size
  186. # 获取图像的原始数据
  187. image_data = np.array(pillow_image)
  188. image_surface = pygame.image.fromstring(image_data.tobytes(), (width, height), 'RGBA').convert_alpha() # 不进行转换会降低效率(?为啥呢)
  189. return image_surface
  190. else:
  191. ...#print(f'打包文件内{filePath}不存在,读取单独文件')
  192. # 没有png文件,返回空
  193. if filePath.endswith('.png') and not os.path.exists(filePath):
  194. #print(filePath, '不存在')
  195. text = '[X]'
  196. font = pygame.font.SysFont('arial', 40)
  197. image_surface = font.render(text, True, (255, 0, 0))
  198. # image_surface = pygame.Surface((40, 40)).convert_alpha()
  199. # image_surface.fill((255, 0, 0))
  200. # print("没找到图片哇:", filePath)
  201. return image_surface
  202. #print(filePath, '读取')
  203. return pygame.image.load(filePath).convert_alpha()
  204. from PIL import Image, ImageTk
  205. import tkinter
  206. def load_png_pillow(filePath:str):
  207. # 首先尝试用json读取,如果失败则尝试用加密方式读取
  208. global imgInitOK, allImgs
  209. if not imgInitOK:
  210. init_img()
  211. #print(f'加载文件{filePath}')
  212. filePath = os.path.normpath(filePath)
  213. if filePath in allImgs.keys():
  214. dataB64 = allImgs[filePath]
  215. image_data = base64.b64decode(dataB64)
  216. # 使用Pillow打开图像
  217. pillow_image = Image.open(io.BytesIO(image_data))
  218. return pillow_image
  219. elif filePath.lower() in allImgs.keys():
  220. dataB64 = allImgs[filePath.lower()]
  221. image_data = base64.b64decode(dataB64)
  222. # 使用Pillow打开图像
  223. pillow_image = Image.open(io.BytesIO(image_data))
  224. return pillow_image
  225. else:
  226. ...#print(f'打包文件内{filePath}不存在,读取单独文件')
  227. # 没有png文件,返回空
  228. if filePath.endswith('.png') and not os.path.exists(filePath):
  229. return
  230. #print(filePath)
  231. return Image.open(filePath)
  232. if __name__=='__main__':
  233. #allJson = init()
  234. #print(allJson)
  235. encrypt_into_onefile()
  236. #init()
  237. encrypt_imgs_into_oneFile()