You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

用Python开发PDX脚本语言自定义编解码器(替代JSON转换)

需求:开发Python模块读写PDX脚本文件

背景

我需要编写一个Python模块,用于读写PDX脚本格式的文件。该格式与JSON类似,但语法差异足够大,必须通过自定义编解码器处理——依赖正则替换的话后续维护会变成噩梦,之前的尝试已经证明了这一点。

最初我尝试将PDX文本转换为合法JSON再处理,但每新增一个小功能都需要编写大量额外代码,维护成本极高。因此现在计划开发自定义编解码器,通过明确合法键值对规则来处理文件,从而减少代码量、简化维护工作。

PDX核心语法示例(非可运行代码)

@key = value # 脚本变量定义

key = {
    # 注释,无多行注释
    function # 单键,通常如optimize_memory

    # 合法键值对,带引号的写法正被淘汰
    key = "value"
    key = value
    key = @key # 使用脚本变量,可在当前文件或`scripted_variables`文件夹中定义
    # type为键类型,例如trigger:planet_stability,其中planet_stability是触发器
    key = type:key

    # 自定义命名变量,多用于标记等场景
    [[VARIABLE_NAME]
        math_key = $VARIABLE_NAME$
    ]

    # 内嵌数学表达式,"<"可替换为任意数学符号,示例:planet_stability < @[ stabilitylevel2 + 10 ]
    key < @[ key + 10 ] 
    
    # 代码块示例:
    # potential = {
    #     exists = owner
    #     owner = {
    #         has_country_flag = flag_name
    #     }
    # }
    key = {
        key = value
    }

    # 列表写法,常用内联括号
    key = { value value }
}

PDX与JSON的关键差异

  • 几乎无需引号包裹键或值
  • 用=替代:分隔键值
  • 行尾不需要逗号

补充语法规则

  • 键值对顺序理论上无要求,但不符合预期顺序会导致模组和冲突解决工具出错
  • 布尔值使用yes/no,而非true/false
  • 要求使用小写,部分场景为必填项
  • 支持>=、<=等数学运算符作为键值分隔符
  • 上述语法未覆盖全部特性,但包含大部分常用场景

过往尝试的问题

我之前尝试将PDX转换为JSON,仅完成了部分工作。比如这段PDX代码:

potential = {
            exists = owner
            owner = {
                is_regular_empire = yes
                is_fallen_empire = no
            }
            NOR = {
                has_modifier = resort_colony
                has_modifier = slave_colony
                uses_habitat_capitals = yes
            }
        }

使用以下代码转换:

test_string = test_string.replace("\n", ",")
        test_string = test_string.replace("{,", "{")
        test_string = test_string.replace("{", "{\n")
        test_string = test_string.replace(",", ",\n")
        test_string = test_string.replace("}, ", "},\n")
        test_string = "{\n" + test_string + "\n}"
        
        # 将等号替换为冒号
        test_string = test_string.replace(" =", ":")

得到的结果:

{
                potential: {
                        exists: owner,
                        owner: {
                                is_regular_empire: yes,     
                                is_fallen_empire: no,       
                        },
                        NOR: {
                                has_modifier: resort_colony,
                                has_modifier: slave_colony, 
                                uses_habitat_capitals: yes, 
                        },
                }
}

该结果接近JSON,但无法自动为键值添加引号,导致转换失败,也凸显了这种方案的工作量极大。因此彻底放弃转JSON的思路,转而开发自定义编解码器。

内容的提问来源于stack exchange,提问作者The Illusion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 09:35:16