import zlib import json import base64 import random import os MAX_ENCRYPT_LENGTH = 2000 ENCRYPT_LENGTH_BYTES = MAX_ENCRYPT_LENGTH.to_bytes(4, 'little') def encrypt_json(data, KEY = 0x20220420): zlibBytes = zlib.compress(json.dumps(data).encode('utf-8')) fileLength = len(zlibBytes) header = b'QQTPVE FILE\x00\x00\x00\x00\x00' # 16字节 fileLength_bytes = fileLength.to_bytes(4, 'little') #print(fileLength, fileLength_bytes) # 将zlibbytes与key_bytes异或 zlibBytes = bytearray(zlibBytes) key_bytes = KEY.to_bytes(4, 'little') for i in range(min(fileLength, MAX_ENCRYPT_LENGTH)): zlibBytes[i] ^= key_bytes[i % 4] # 尾部随便增加一些字节,防止解密时越界 for i in range(random.randint(0, 100)): zlibBytes += random.randint(0, 100).to_bytes(1, 'little') finByets = header + fileLength_bytes + ENCRYPT_LENGTH_BYTES + zlibBytes #print(finByets[:24]) return finByets def decrypt_json(data, KEY = 0x20220420): header = data[:16] key_bytes = KEY.to_bytes(4, 'little') fileLength_bytes = data[16:20] fileLength = int.from_bytes(fileLength_bytes, 'little') entryptLength_bytes = data[20:24] entryptLength = int.from_bytes(entryptLength_bytes, 'little') #print(entryptLength_bytes,entryptLength) zlibBytes = data[24:24 + fileLength] #print(header,fileLength, fileLength_bytes) # 将zlibbytes与key_bytes异或 zlibBytes = bytearray(zlibBytes) for i in range(min(fileLength,entryptLength)): zlibBytes[i] ^= key_bytes[i % 4] zlibBytes = zlibBytes[:fileLength] # print(zlibBytes) decompressed_data = zlib.decompress(zlibBytes) json_data = json.loads(decompressed_data.decode('utf-8')) # print(json_data) return json_data def load_json(filePath:str): # 首先尝试读取加密文件,如果没有则去真实路径读取 global initOK if not initOK: init() # print(f'加载文件{filePath}') filePath = os.path.normpath(filePath) if filePath in allJson.keys(): return allJson[filePath] elif filePath.lower() in allJson.keys(): return allJson[filePath.lower()] else: ...# print(f'打包文件内{filePath}不存在,读取单独文件') # print(filePath) if os.path.exists(filePath) and filePath !='.': try: with open(filePath, 'r', encoding='utf-8') as f: data:dict = json.load(f) except: with open(filePath, 'r', encoding='utf-8_sig') as f: data:dict = json.load(f) else: data = {} return data def encrypt_into_onefile(): import os if not os.path.exists('gameFiles'): os.mkdir('gameFiles') data = {} for root, dirs, files in os.walk('./game'): for file in files: if file.endswith('.json'): with open(os.path.join(root, file), 'r', encoding='utf-8') as f: filePath = os.path.join(root, file) filePath = os.path.normpath(filePath).lower() data[filePath] = json.load(f) data = encrypt_json(data) with open('game.pveres', 'wb') as f: f.write(data) initOK = False allJson = {} def init(): '''读取gameFiles文件夹下的所有文件,解密并通过update保存到一个字典''' import os data = {} if os.path.exists('game.pveres'): print('读取默认游戏地图中...') with open('game.pveres', 'rb') as f: data.update(decrypt_json(f.read())) for root, dirs, files in os.walk('game/gameFiles'): for file in files: if file.endswith('.pveres'): with open(os.path.join(root, file), 'rb') as f: try: data.update(decrypt_json(f.read())) # print(f'读取{file}...') except: # print(f'读取{file}失败') ...#print(f'读取{file}失败') global initOK, allJson allJson = data initOK = True # with open('allFiles.json', 'w') as f: # json.dump(list(allJson.keys()), f) import base64 def encrypt_imgs_into_oneFile(): '''读取所有图片文件,根据路径生成字典,加密后保存到一个文件''' data = {} totalFileNum = 0 for root, dirs, files in os.walk('./res'): for file in files: if file.endswith('.png'): totalFileNum += 1 # print(f'共有{totalFileNum}个文件') i = 0 for root, dirs, files in os.walk('./res'): for file in files: if file.endswith('.png'): filePath = os.path.join(root, file) filePath = os.path.normpath(filePath).lower() with open(filePath, 'rb') as f: data[filePath] = base64.b64encode(f.read()).decode('utf-8') if i%100 == 0: print(f'{i}/{totalFileNum} 读取{filePath}') i += 1 data = encrypt_json(data) with open('game_imgs.pveimg', 'wb') as f: f.write(data) imgInitOK = False allImgs = {} def init_img(): '''读取gameFiles文件夹下的所有文件,解密并通过update保存到一个字典''' import os data = {} global imgInitOK, allImgs if os.path.exists('game_imgs.pveimg'): print('读取默认游戏素材中...') with open('game_imgs.pveimg', 'rb') as f: data.update(decrypt_json(f.read())) for root, dirs, files in os.walk('game/gameFiles'): for file in files: if file.endswith('.pveimg'): # print(f'读取{file}...') with open(os.path.join(root, file), 'rb') as f: data.update(decrypt_json(f.read())) allImgs = data imgInitOK = True # with open('allImgs.json', 'w') as f: # json.dump(list(allImgs.keys()), f) # print(allImgs.keys()[0]) import pygame import numpy as np from PIL import Image import io def load_png(filePath:str): # 首先尝试读取加密文件,如果没有则去真实路径读取 global imgInitOK, allImgs if not imgInitOK: init_img() #print(f'加载文件{filePath}') filePath = os.path.normpath(filePath) if filePath.lower() in allImgs.keys(): dataB64 = allImgs[filePath.lower()] image_data = base64.b64decode(dataB64) # 使用Pillow打开图像 pillow_image = Image.open(io.BytesIO(image_data)) pillow_image = pillow_image.convert("RGBA") # 获取图像的大小 width, height = pillow_image.size # 获取图像的原始数据 image_data = np.array(pillow_image) image_surface = pygame.image.fromstring(image_data.tobytes(), (width, height), 'RGBA').convert_alpha() # 不进行转换会降低效率(?为啥呢) return image_surface elif filePath in allImgs.keys(): dataB64 = allImgs[filePath] image_data = base64.b64decode(dataB64) # 使用Pillow打开图像 pillow_image = Image.open(io.BytesIO(image_data)) pillow_image = pillow_image.convert("RGBA") # 获取图像的大小 width, height = pillow_image.size # 获取图像的原始数据 image_data = np.array(pillow_image) image_surface = pygame.image.fromstring(image_data.tobytes(), (width, height), 'RGBA').convert_alpha() # 不进行转换会降低效率(?为啥呢) return image_surface else: ...#print(f'打包文件内{filePath}不存在,读取单独文件') # 没有png文件,返回空 if filePath.endswith('.png') and not os.path.exists(filePath): #print(filePath, '不存在') text = '[X]' font = pygame.font.Font(None, 40) image_surface = font.render(text, True, (255, 0, 0)) # image_surface = pygame.Surface((40, 40)).convert_alpha() # image_surface.fill((255, 0, 0)) # print("没找到图片哇:", filePath) return image_surface #print(filePath, '读取') return pygame.image.load(filePath).convert_alpha() from PIL import Image, ImageTk import tkinter def load_png_pillow(filePath:str): # 首先尝试用json读取,如果失败则尝试用加密方式读取 global imgInitOK, allImgs if not imgInitOK: init_img() #print(f'加载文件{filePath}') filePath = os.path.normpath(filePath) if filePath in allImgs.keys(): dataB64 = allImgs[filePath] image_data = base64.b64decode(dataB64) # 使用Pillow打开图像 pillow_image = Image.open(io.BytesIO(image_data)) return pillow_image elif filePath.lower() in allImgs.keys(): dataB64 = allImgs[filePath.lower()] image_data = base64.b64decode(dataB64) # 使用Pillow打开图像 pillow_image = Image.open(io.BytesIO(image_data)) return pillow_image else: ...#print(f'打包文件内{filePath}不存在,读取单独文件') # 没有png文件,返回空 if filePath.endswith('.png') and not os.path.exists(filePath): return #print(filePath) return Image.open(filePath) if __name__=='__main__': #allJson = init() #print(allJson) encrypt_into_onefile() #init() encrypt_imgs_into_oneFile()