维护提醒

BWIKI 全站将于 9 月 3 日(全天)进行维护,期间无法编辑任何页面或发布新的评论。

全站通知:

模块:Talk/data/doc

来自星露谷物语维基
跳到导航 跳到搜索
[ 刷新 ]
当前页面是文档页面,会被模块:Talk/data引入。查看模板:Documentation获取更多信息。

文件列表

  • Abigail.zh-CN.json
  • Alex.zh-CN.json
  • Caroline.zh-CN.json
  • Clint.zh-CN.json
  • Demetrius.zh-CN.json
  • Dwarf.zh-CN.json
  • Elliott.zh-CN.json
  • Emily.zh-CN.json
  • EngagementDialogue.zh-CN.json
  • Evelyn.zh-CN.json
  • ExtraDialogue.zh-CN.json
  • George.zh-CN.json
  • Gil.zh-CN.json
  • Gus.zh-CN.json
  • Haley.zh-CN.json
  • Harvey.zh-CN.json
  • Jas.zh-CN.json
  • Jodi.zh-CN.json
  • Kent.zh-CN.json
  • Krobus.zh-CN.json
  • Leah.zh-CN.json
  • Leo.zh-CN.json
  • LeoMainland.zh-CN.json
  • Lewis.zh-CN.json
  • Linus.zh-CN.json
  • Locations.json
  • Marnie.zh-CN.json
  • MarriageDialogue.zh-CN.json
  • MarriageDialogueAbigail.zh-CN.json
  • MarriageDialogueAlex.zh-CN.json
  • MarriageDialogueElliott.zh-CN.json
  • MarriageDialogueEmily.zh-CN.json
  • MarriageDialogueHaley.zh-CN.json
  • MarriageDialogueHarvey.zh-CN.json
  • MarriageDialogueKrobus.zh-CN.json
  • MarriageDialogueLeah.zh-CN.json
  • MarriageDialogueMaru.zh-CN.json
  • MarriageDialoguePenny.zh-CN.json
  • MarriageDialogueSam.zh-CN.json
  • MarriageDialogueSebastian.zh-CN.json
  • MarriageDialogueShane.zh-CN.json
  • Maru.zh-CN.json
  • merged_dialogues.json
  • Mister Qi.zh-CN.json
  • MovieReactions.zh-CN.json
  • Pam.zh-CN.json
  • Penny.zh-CN.json
  • Pierre.zh-CN.json
  • rainy.zh-CN.json
  • Robin.zh-CN.json
  • Sam.zh-CN.json
  • Sandy.zh-CN.json
  • Sebastian.zh-CN.json
  • Shane.zh-CN.json
  • Vincent.zh-CN.json
  • Willy.zh-CN.json
  • Wizard.zh-CN.json
  • WorldMap.json
  • Events\AbandonedJojaMart.zh-CN.json
  • Events\AnimalShop.zh-CN.json
  • Events\ArchaeologyHouse.zh-CN.json
  • Events\Backwoods.zh-CN.json
  • Events\BathHouse_Pool.zh-CN.json
  • Events\Beach.zh-CN.json
  • Events\BoatTunnel.zh-CN.json
  • Events\BusStop.zh-CN.json
  • Events\CommunityCenter.zh-CN.json
  • Events\DesertFestival.zh-CN.json
  • Events\ElliottHouse.zh-CN.json
  • Events\Farm.zh-CN.json
  • Events\FarmHouse.zh-CN.json
  • Events\FishShop.zh-CN.json
  • Events\Forest.zh-CN.json
  • Events\HaleyHouse.zh-CN.json
  • Events\HarveyRoom.zh-CN.json
  • Events\Hospital.zh-CN.json
  • Events\IslandHut.zh-CN.json
  • Events\IslandNorth.zh-CN.json
  • Events\IslandSouth.zh-CN.json
  • Events\IslandWest.zh-CN.json
  • Events\JoshHouse.zh-CN.json
  • Events\LeahHouse.zh-CN.json
  • Events\ManorHouse.zh-CN.json
  • Events\Mine.zh-CN.json
  • Events\Mountain.zh-CN.json
  • Events\QiNutRoom.zh-CN.json
  • Events\Railroad.zh-CN.json
  • Events\Saloon.zh-CN.json
  • Events\SamHouse.zh-CN.json
  • Events\SandyHouse.zh-CN.json
  • Events\ScienceHouse.zh-CN.json
  • Events\SebastianRoom.zh-CN.json
  • Events\SeedShop.zh-CN.json
  • Events\Sewer.zh-CN.json
  • Events\Sunroom.zh-CN.json
  • Events\Temp.zh-CN.json
  • Events\Tent.zh-CN.json
  • Events\Town.zh-CN.json
  • Events\Trailer.zh-CN.json
  • Events\Trailer_Big.zh-CN.json
  • Events\WizardHouse.zh-CN.json
  • Events\Woods.zh-CN.json
  • Festivals\fall16.zh-CN.json
  • Festivals\fall27.zh-CN.json
  • Festivals\FestivalDates.zh-CN.json
  • Festivals\spring13.zh-CN.json
  • Festivals\spring24.zh-CN.json
  • Festivals\summer11.zh-CN.json
  • Festivals\summer28.zh-CN.json
  • Festivals\winter25.zh-CN.json
  • Festivals\winter8.zh-CN.json
  • schedules\Abigail.zh-CN.json
  • schedules\Alex.zh-CN.json
  • schedules\Caroline.zh-CN.json
  • schedules\Clint.zh-CN.json
  • schedules\Demetrius.zh-CN.json
  • schedules\Elliott.zh-CN.json
  • schedules\Emily.zh-CN.json
  • schedules\Evelyn.zh-CN.json
  • schedules\George.zh-CN.json
  • schedules\Gus.zh-CN.json
  • schedules\Haley.zh-CN.json
  • schedules\Harvey.zh-CN.json
  • schedules\Jas.zh-CN.json
  • schedules\Jodi.zh-CN.json
  • schedules\Leah.zh-CN.json
  • schedules\Leo.zh-CN.json
  • schedules\Lewis.zh-CN.json
  • schedules\Linus.zh-CN.json
  • schedules\Marnie.zh-CN.json
  • schedules\Maru.zh-CN.json
  • schedules\Pam.zh-CN.json
  • schedules\Penny.zh-CN.json
  • schedules\Pierre.zh-CN.json
  • schedules\Robin.zh-CN.json
  • schedules\Sam.zh-CN.json
  • schedules\Sandy.zh-CN.json
  • schedules\Sebastian.zh-CN.json
  • schedules\Shane.zh-CN.json
  • schedules\Vincent.zh-CN.json
  • schedules\Willy.zh-CN.json
  • Strings\1_6_Strings.zh-CN.json
  • Strings\animationDescriptions.zh-CN.json
  • Strings\Characters.zh-CN.json
  • Strings\Events.zh-CN.json
  • Strings\SpeechBubbles.zh-CN.json
  • Strings\StringsFromCSFiles.zh-CN.json

文件转换

import os
import json
from pathlib import Path

def merge_dialogue_files():
    """
    遍历指定目录下的所有.zh-CN.json文件并合并到一个文件中
    """
    base_dir = Path(r"\Talk")
    output_file = base_dir / "merged_dialogues.json"
    
    merged_data = {}
    processed_files = []
    
    print("开始扫描对话文件...")
    
    # 递归遍历所有.zh-CN.json文件
    for json_file in base_dir.rglob("*.zh-CN.json"):
        try:
            # 获取相对于基础目录的文件名作为key,并移除.zh-CN.json后缀
            relative_path = json_file.relative_to(base_dir)
            file_key = str(relative_path).replace("\\", "/")  # 使用正斜杠作为分隔符
            
            # 移除.zh-CN.json后缀
            if file_key.endswith(".zh-CN.json"):
                file_key = file_key.replace(".zh-CN.json", "")  # 安全地移除后缀
            
            print(f"处理文件: {file_key}")
            
            # 读取JSON文件
            with open(json_file, 'r', encoding='utf-8') as f:
                file_content = json.load(f)
            
            # 将文件内容存储到合并数据中
            merged_data[file_key] = file_content
            processed_files.append(file_key)
            
        except Exception as e:
            print(f"处理文件 {json_file} 时出错: {e}")
            continue
    
    # 保存合并后的文件
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(merged_data, f, ensure_ascii=False, indent=2)
        
        print(f"\n合并完成!")
        print(f"合并了 {len(processed_files)} 个文件")
        print(f"输出文件: {output_file}")
        print(f"文件大小: {output_file.stat().st_size / 1024 / 1024:.2f} MB")
        
        print("\n已处理的文件列表:")
        for file_key in sorted(processed_files):
            print(f"  - {file_key}")
            
        return str(output_file)
        
    except Exception as e:
        print(f"保存合并文件时出错: {e}")
        return None

if __name__ == "__main__":
    print("=== 对话文件合并工具 ===")
    
    # 执行合并
    merged_file = merge_dialogue_files()
    
    if merged_file:
        print(f"\n✅ 合并完成!")
    else:
        print(f"\n❌ 合并失败!")
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
JSON 转 Lua 转换器
将 merged_dialogues.json 转换为 Talk/data 格式
"""

import json
import os
import re
from typing import Dict, Any


def escape_lua_string(s: str) -> str:
    """
    转义 Lua 字符串中的特殊字符
    
    Args:
        s: 原始字符串
        
    Returns:
        str: 转义后的字符串
    """
    if not isinstance(s, str):
        return str(s)
    
    # 转义反斜杠和引号
    s = s.replace('\\', '\\\\')
    s = s.replace('"', '\\"')
    s = s.replace('\n', '\\n')
    s = s.replace('\r', '\\r')
    s = s.replace('\t', '\\t')
    
    return s


def is_lua_keyword(s: str) -> bool:
    """
    检查字符串是否为 Lua 关键字

    Args:
        s: 要检查的字符串

    Returns:
        bool: 如果是 Lua 关键字返回 True
    """
    lua_keywords = {
        'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for',
        'function', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
        'return', 'then', 'true', 'until', 'while'
    }
    return s in lua_keywords


def format_lua_table_value(value: Any, indent_level: int = 0) -> str:
    """
    将 Python 值格式化为 Lua 表格式

    Args:
        value: 要格式化的值
        indent_level: 缩进级别

    Returns:
        str: 格式化后的 Lua 值
    """
    indent = "\t" * indent_level
    
    if isinstance(value, dict):
        if not value:
            return "{}"
        
        lines = ["{"]
        for k, v in value.items():
            # 检查键名是否需要用引号括起来
            # 条件:不是有效标识符、以数字开头、或者是 Lua 关键字
            if not k.isidentifier() or re.match(r'^\d', k) or is_lua_keyword(k):
                key_str = f'["{escape_lua_string(k)}"]'
            else:
                key_str = k
            value_str = format_lua_table_value(v, indent_level + 1)
            lines.append(f"{indent}\t{key_str} = {value_str},")
        lines.append(f"{indent}}}")
        return "\n".join(lines)
    
    elif isinstance(value, (list, tuple)):
        if not value:
            return "{}"
        
        lines = ["{"]
        for item in value:
            value_str = format_lua_table_value(item, indent_level + 1)
            lines.append(f"{indent}\t{value_str},")
        lines.append(f"{indent}}}")
        return "\n".join(lines)
    
    elif isinstance(value, str):
        return f'"{escape_lua_string(value)}"'
    
    elif isinstance(value, bool):
        return "true" if value else "false"
    
    elif isinstance(value, (int, float)):
        return str(value)
    
    elif value is None:
        return "nil"
    
    else:
        return f'"{escape_lua_string(str(value))}"'


def convert_json_to_lua(json_file: str, output_file: str) -> None:
    """
    将 JSON 文件转换为 Lua 数据文件
    
    Args:
        json_file: 输入的 JSON 文件路径
        output_file: 输出的 Lua 文件路径
    """
    try:
        # 读取 JSON 文件
        with open(json_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        print(f"成功读取 JSON 文件,包含 {len(data)} 个顶级键")
        
        # 创建输出目录
        output_dir = os.path.dirname(output_file)
        if output_dir and not os.path.exists(output_dir):
            os.makedirs(output_dir)
            print(f"创建目录: {output_dir}")
        
        # 生成 Lua 文件内容
        lua_content = []

        lua_content.append("local data = " + format_lua_table_value(data))
        lua_content.append("")
        lua_content.append("return data")
        
        # 写入 Lua 文件
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write("\n".join(lua_content))
        
        print(f"成功生成 Lua 文件: {output_file}")
        print(f"文件大小: {os.path.getsize(output_file)} 字节")
        
    except FileNotFoundError:
        print(f"错误: 找不到输入文件 {json_file}")
    except json.JSONDecodeError as e:
        print(f"错误: JSON 解析失败 - {e}")
    except Exception as e:
        print(f"错误: {e}")


def main():
    """主函数"""
    current_dir = os.path.dirname(os.path.abspath(__file__))
    json_file = os.path.join(current_dir, "merged_dialogues.json")
    output_file = os.path.join(current_dir, "Talk", "Data.lua")
    
    print("JSON 转 Lua 转换器")
    print("=" * 30)
    print(f"输入文件: {json_file}")
    print(f"输出文件: {output_file}")
    print()
    
    convert_json_to_lua(json_file, output_file)


if __name__ == "__main__":
    main()