如何对字典进行Base64编码后写入文件,再解码并将其内容转为游戏变量?
如何对字典进行Base64编码后写入文件,再解码并将其内容转为游戏变量?
嘿,刚好我之前做文字冒险游戏的时候也搞过类似的存档功能,给你梳理一套完整的实现思路,用Python来演示的话,完全适配你的需求:
一、编码保存游戏状态到文件
核心思路就是把你的游戏变量先打包成字典,转成JSON字符串,再转成字节做Base64编码,最后写入文件。具体步骤和代码如下:
import json import base64 # 先把你的游戏变量整理成一个字典(和你给出的JSON结构一致) game_state = { "hd1": True, "hd2": True, "hd3": False, "hd4": False, "hd5": False, "P1": "Unlocked", "P2": "Unlocked", "P3": "Unlocked", "P4": "Locked", "P5": "Locked", "Inv": [ "Killed my wife, my name is John. \n John created the safe // The code to the SAFE is 728 and the code to the LOCK is 1538 // Born on the 6th of November", "If you have found this letter, good, help me, I think I have gone south to the nearby yellow tree, PLEASE HELP!! \n Suit of Sir John the Great // The sky seems blue today, I'm wearing a red coat and some cargo green trousers, the sun looks more yellow today too" ] } # 1. 把字典转成JSON字符串(序列化) json_state = json.dumps(game_state) # 2. 把字符串转成字节(Base64只能处理字节数据) byte_state = json_state.encode('utf-8') # 3. 对字节做Base64编码 encoded_state = base64.b64encode(byte_state) # 4. 写入存档文件(用.sav后缀更有游戏存档的感觉) with open('game_save.sav', 'wb') as save_file: save_file.write(encoded_state)
二、解码加载存档到游戏变量
重启游戏时,读取存档文件,解码Base64,转成JSON字典,再把值赋值给你的游戏变量:
import json import base64 # 1. 读取存档文件里的Base64编码字节 with open('game_save.sav', 'rb') as save_file: encoded_state = save_file.read() # 2. 解码Base64得到JSON字节 decoded_byte_state = base64.b64decode(encoded_state) # 3. 把字节转成JSON字符串 decoded_json_state = decoded_byte_state.decode('utf-8') # 4. 把JSON字符串转成字典(反序列化) loaded_game_state = json.loads(decoded_json_state) # 5. 把字典里的内容赋值给你的游戏变量 hd1 = loaded_game_state['hd1'] hd2 = loaded_game_state['hd2'] hd3 = loaded_game_state['hd3'] hd4 = loaded_game_state['hd4'] hd5 = loaded_game_state['hd5'] P1 = loaded_game_state['P1'] P2 = loaded_game_state['P2'] P3 = loaded_game_state['P3'] P4 = loaded_game_state['P4'] P5 = loaded_game_state['P5'] Inventory = loaded_game_state['Inv'] # 测试一下加载结果 print("加载的Inventory内容:", Inventory)
一些小提示
- Base64只是编码不是加密,玩家如果懂技术还是能修改存档,要是想防篡改,可以额外加个哈希校验(比如用hashlib生成状态的哈希值一起存,加载时对比),不过如果只是普通存档需求,Base64完全够用。
- JSON对列表、字典的序列化/反序列化支持很好,你的Inventory列表里的换行和特殊字符都能被正确保存和读取,不用担心丢失内容。
- 存档文件的后缀可以随便选,.sav、.txt都可以,用.sav更符合游戏存档的直观感受。
备注:内容来源于stack exchange,提问作者EldonHD
相关产品推荐
相关产品推荐

