import zlib import json import base64 import random import os import pygame import numpy as np import io import game.const.rouge as R from PIL import Image user_documents_folder = os.path.expanduser("~\\Documents") # 获取用户的"文档"文件夹路径 qqtpve_folder = os.path.join(user_documents_folder, "QQTPVE") # 构建QQTPVE文件夹路径 os.makedirs(qqtpve_folder, exist_ok=True) # 确保QQTPVE文件夹存在,如果不存在则创建 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(filePath, allJson.keys()) # print(f'加载文件{filePath}') filePath = os.path.normpath(filePath) # print(allJson.keys()) # print(filePath, filePath in allJson.keys()) if filePath in allJson.keys(): return allJson[filePath] elif filePath.lower() in allJson.keys(): return allJson[filePath.lower()] else: # print(allJson.keys()) if R.print_mode: print(f'打包文件内{filePath}不存在,读取单独文件') ...# print(f'打包文件内{filePath}不存在,读取单独文件') # print(allJson.keys()) try: with open(filePath, 'r', encoding='utf-8') as f: data = json.load(f) except Exception as e: with open(filePath, 'r', encoding='utf-8_sig') as f: data = json.load(f) return data def load_rouge_data(filePath:str): # 首先尝试读取加密文件,如果没有则去真实路径读取 import logging r_data = {} for root, dirs, files in os.walk(qqtpve_folder): for file in files: if file.endswith('.rougedata'): with open(os.path.join(root, file), 'rb') as f: try: r_data.update(decrypt_json(f.read())) # print(f'读取{file}...') except Exception as e: logging.error(f"读取{file}发生错误: {e}") ...#print(f'读取{file}失败') filePath = os.path.normpath(filePath) if filePath in r_data.keys(): return r_data[filePath] elif filePath.lower() in r_data.keys(): return r_data[filePath.lower()] else: ...# print(f'打包文件内{filePath}不存在,读取单独文件') try: with open(filePath, 'r', encoding='utf-8') as f: data = json.load(f) except: with open(filePath, 'r', encoding='utf-8_sig') as f: data = json.load(f) return data def save_encrypt_single_rouge_file(fileData, fileName:str): if not os.path.exists('game/rougeLocalData'): os.mkdir('game/rougeLocalData') data = {} # 加载文件内容到字典 data[qqtpve_folder+"\\"+fileName+".rougedata"] = fileData # print(data) # 加密数据 encrypted_data = encrypt_json(data) # 生成加密文件的名称 encryptedFileName = f'{qqtpve_folder}/{fileName}.rougedata' localEncryptedFileName = f'game/rougeLocalData/{fileName}.rougedata' # 尝试删除已存在的文件 ''' for file_path in [encryptedFileName, localEncryptedFileName]: try: if os.path.exists(file_path): os.remove(file_path) except Exception as e: print(f"删除旧文件时发生错误:{e}") return None ''' # 保存 try: with open(encryptedFileName, 'wb') as f: f.write(encrypted_data) # print(f'肉鸽加密文件已保存为: {encryptedFileName}') except Exception as e: print(f"保存加密肉鸽文件时发生错误:{e}") return None try: with open(localEncryptedFileName, 'wb') as f: f.write(encrypted_data) # print(f'肉鸽加密文件已保存为: {localEncryptedFileName}') except Exception as e: print(f"保存加密肉鸽文件时发生错误:{e}") return None def encrypt_into_onefile(): 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保存到一个字典 ''' global initOK, allJson data = {} # ''' for root, dirs, files in os.walk(qqtpve_folder): for file in files: if file.endswith('.rougedata'): 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}失败') # ''' if os.path.exists('game.pveres'): # print('读取默认游戏地图中...') with open('game.pveres', 'rb') as f: data.update(decrypt_json(f.read())) # else: # print(f"game.pveres 不存在") for root, dirs, files in os.walk('game/gameFiles'): for file in files: if file.endswith('.pveres'): # print(f"load file: {file}") with open(os.path.join(root, file), 'rb') as f: try: # os.path.normpath(filePath) data.update(decrypt_json(f.read())) # print(f'读取{file}...') except Exception as e: print(f'读取{file}失败, error: {e}') ...#print(f'读取{file}失败') allJson = data # print(allJson.keys()) initOK = True 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]) 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.SysFont('arial', 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()