Commit 36871597 authored by 苍蓝's avatar 苍蓝

更新 deckcode.py

parent 64f69609
import os import os
import sys
import urllib.request import urllib.request
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import Dict, Optional
from pathlib import Path
# 设置文件夹和文件路径 # 配置
folder_path = "deck" CONFIG = {
formal_file = "to-formal.txt" 'folder_path': "deck",
pre_file = "to-pre.txt" 'formal_file': "to-formal.txt",
url_formal = "https://code.moenext.com/coccvo/card-password-conversion/-/raw/master/to-formal.txt" 'pre_file': "to-pre.txt",
url_pre = "https://code.moenext.com/coccvo/card-password-conversion/-/raw/master/to-pre.txt" 'url_formal': "https://code.moenext.com/coccvo/card-password-conversion/-/raw/master/to-formal.txt",
'url_pre': "https://code.moenext.com/coccvo/card-password-conversion/-/raw/master/to-pre.txt"
}
# 检查 deck 文件夹是否存在 def check_and_update_file(filename: str, url: str) -> bool:
if not os.path.exists(folder_path): """检查并更新文件,如果成功返回True,失败返回False"""
print("Error: 请把此文件放到游戏目录中再运行")
input("按回车键退出...")
exit(1)
# 定义一个函数来下载对照表
def download_file(url, filename):
try: try:
urllib.request.urlretrieve(url, filename)
except Exception as e:
print(f"Error: 下载对照表失败 {e}")
input("按回车键退出...")
exit(1)
# 检查对照表文件是否存在,以及是否需要更新
def check_and_update_file(filename, url):
if not os.path.exists(filename): if not os.path.exists(filename):
print(f"{filename} 不存在,开始下载...") print(f"{filename} 不存在,开始下载...")
download_file(url, filename) return download_file(url, filename)
else:
file_mod_time = datetime.fromtimestamp(os.path.getmtime(filename)) file_mod_time = datetime.fromtimestamp(os.path.getmtime(filename))
current_time = datetime.now() current_time = datetime.now()
if (current_time - file_mod_time) > timedelta(days=1): if (current_time - file_mod_time) > timedelta(days=1):
print(f"更新 {filename}...") print(f"更新 {filename}...")
download_file(url, filename) return download_file(url, filename)
return True
except Exception as e:
print(f"Error: 检查文件更新失败 {e}")
return False
# 更新对照表文件 def download_file(url: str, filename: str) -> bool:
check_and_update_file(formal_file, url_formal) try:
check_and_update_file(pre_file, url_pre) urllib.request.urlretrieve(url, filename)
return True
except Exception as e:
print(f"Error: 下载对照表失败 {e}")
return False
# 读取对照表并构建替换规则字典
replacements = {} def load_replacements(formal_file: str, pre_file: str) -> Optional[Dict[str, str]]:
with open(formal_file, 'r', encoding='utf-8') as file: try:
replacements = {}
# 读取正式对照表
with open(formal_file, 'r', encoding='utf-8') as file:
for line in file: for line in file:
parts = line.strip().split('\t') parts = line.strip().split('\t')
if len(parts) == 2: if len(parts) == 2:
replacements[parts[0]] = parts[1] replacements[parts[0]] = parts[1]
# 逆向读取第二个对照表 # 读取预发布对照表
with open(pre_file, 'r', encoding='utf-8') as file: with open(pre_file, 'r', encoding='utf-8') as file:
for line in file: for line in file:
parts = line.strip().split('\t') parts = line.strip().split('\t')
if len(parts) == 2: if len(parts) == 2:
replacements[parts[1]] = parts[0] replacements[parts[1]] = parts[0]
# 遍历deck文件夹中的所有.ydk文件 return replacements
for root, dirs, files in os.walk(folder_path): except Exception as e:
for file in files: print(f"Error: 读取对照表失败 {e}")
if file.endswith(".ydk"): return None
file_path = os.path.join(root, file)
with open(file_path, 'r', encoding='utf-8') as f: def main() -> int:
original_content = f.read() # 检查目录
if not os.path.exists(CONFIG['folder_path']):
print("Error: 请把此文件放到游戏目录中再运行")
return 1
# 更新对照表
for file_key, url_key in [('formal_file', 'url_formal'), ('pre_file', 'url_pre')]:
if not check_and_update_file(CONFIG[file_key], CONFIG[url_key]):
return 1
# 替换文本 # 加载替换规则
new_content = original_content replacements = load_replacements(CONFIG['formal_file'], CONFIG['pre_file'])
if not replacements:
return 1
# 处理卡组文件
deck_path = Path(CONFIG['folder_path'])
for ydk_file in deck_path.rglob('*.ydk'):
try:
content = ydk_file.read_text(encoding='utf-8')
new_content = content
for old, new in replacements.items(): for old, new in replacements.items():
new_content = new_content.replace(old, new) new_content = new_content.replace(old, new)
# 仅当内容发生变化时才写回文件 if new_content != content:
if new_content != original_content: ydk_file.write_text(new_content, encoding='utf-8')
with open(file_path, 'w', encoding='utf-8') as f: print(f"更新卡组: {ydk_file}")
f.write(new_content)
print(f"更新卡组: {file_path}")
else: else:
print(f"卡组无需修改: {file_path}") print(f"卡组无需修改: {ydk_file}")
except Exception as e:
print(f"处理文件 {ydk_file} 时出错: {e}")
continue
print("卡组更新完成。") print("卡组更新完成。")
input("按回车键退出...") return 0
if __name__ == "__main__":
try:
exit_code = main()
print("\n按回车键退出...")
input()
sys.exit(exit_code) # 使用 sys.exit() 替代 exit()
except Exception as e:
print(f"Error: {e}")
print("\n按回车键退出...")
input()
sys.exit(1)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment