Commit 36871597 authored by 苍蓝's avatar 苍蓝

更新 deckcode.py

parent 64f69609
import os
import sys
import urllib.request
from datetime import datetime, timedelta
from typing import Dict, Optional
from pathlib import Path
# 设置文件夹和文件路径
folder_path = "deck"
formal_file = "to-formal.txt"
pre_file = "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"
# 配置
CONFIG = {
'folder_path': "deck",
'formal_file': "to-formal.txt",
'pre_file': "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 文件夹是否存在
if not os.path.exists(folder_path):
print("Error: 请把此文件放到游戏目录中再运行")
input("按回车键退出...")
exit(1)
# 定义一个函数来下载对照表
def download_file(url, filename):
def check_and_update_file(filename: str, url: str) -> bool:
"""检查并更新文件,如果成功返回True,失败返回False"""
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):
print(f"{filename} 不存在,开始下载...")
download_file(url, filename)
else:
if not os.path.exists(filename):
print(f"{filename} 不存在,开始下载...")
return download_file(url, filename)
file_mod_time = datetime.fromtimestamp(os.path.getmtime(filename))
current_time = datetime.now()
if (current_time - file_mod_time) > timedelta(days=1):
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:
try:
urllib.request.urlretrieve(url, filename)
return True
except Exception as e:
print(f"Error: 下载对照表失败 {e}")
return False
def load_replacements(formal_file: str, pre_file: str) -> Optional[Dict[str, str]]:
try:
replacements = {}
# 读取正式对照表
with open(formal_file, 'r', encoding='utf-8') as file:
for line in file:
parts = line.strip().split('\t')
if len(parts) == 2:
replacements[parts[0]] = parts[1]
# 更新对照表文件
check_and_update_file(formal_file, url_formal)
check_and_update_file(pre_file, url_pre)
# 读取预发布对照表
with open(pre_file, 'r', encoding='utf-8') as file:
for line in file:
parts = line.strip().split('\t')
if len(parts) == 2:
replacements[parts[1]] = parts[0]
return replacements
except Exception as e:
print(f"Error: 读取对照表失败 {e}")
return None
# 读取对照表并构建替换规则字典
replacements = {}
with open(formal_file, 'r', encoding='utf-8') as file:
for line in file:
parts = line.strip().split('\t')
if len(parts) == 2:
replacements[parts[0]] = parts[1]
def main() -> int:
# 检查目录
if not os.path.exists(CONFIG['folder_path']):
print("Error: 请把此文件放到游戏目录中再运行")
return 1
# 逆向读取第二个对照表
with open(pre_file, 'r', encoding='utf-8') as file:
for line in file:
parts = line.strip().split('\t')
if len(parts) == 2:
replacements[parts[1]] = parts[0]
# 更新对照表
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
# 遍历deck文件夹中的所有.ydk文件
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith(".ydk"):
file_path = os.path.join(root, file)
with open(file_path, 'r', encoding='utf-8') as f:
original_content = f.read()
# 加载替换规则
replacements = load_replacements(CONFIG['formal_file'], CONFIG['pre_file'])
if not replacements:
return 1
# 替换文本
new_content = original_content
# 处理卡组文件
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():
new_content = new_content.replace(old, new)
# 仅当内容发生变化时才写回文件
if new_content != original_content:
with open(file_path, 'w', encoding='utf-8') as f:
f.write(new_content)
print(f"更新卡组: {file_path}")
if new_content != content:
ydk_file.write_text(new_content, encoding='utf-8')
print(f"更新卡组: {ydk_file}")
else:
print(f"卡组无需修改: {file_path}")
print(f"卡组无需修改: {ydk_file}")
except Exception as e:
print(f"处理文件 {ydk_file} 时出错: {e}")
continue
print("卡组更新完成。")
return 0
print("卡组更新完成。")
input("按回车键退出...")
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