写一个模块
从零到能被装起来的模块骨架,以及装载期的那些硬性检查。
目录长什么样
mods/examples/hello/
mod.toml 声明
mod.py 实现
各层目录不需要 __init__.py(Python 命名空间包)。Entry 里的路径按仓库根解析。
声明
[Mod]
Id = "example:hello"
Version = "1.0.0"
Entry = "mods.examples.hello.mod:HelloMod"
Requires = []
[State]
Owns = ["hello"]
[Capabilities]
Provides = ["example:hello"]
Id 用自己的命名空间(example:、yourname:),别跟 native 的 native: 撞。
实现
from engine.runtime import GameMod, Tool
class HelloMod(GameMod):
def mixins(self):
return () # 必填:返回混入 World 的类
def initialize_world(self, world):
world.hello = {} # 世界建好后调用一次
def objects(self, world):
return {'example:hello': world.hello} # 能力名 → 对象
def tools(self):
return (Tool('hello_add', self._add, description='给本国加一个数。'),
Tool('hello_total', self._total, read_only=True, description='看所有国家的总数。'))
@staticmethod
def _add(world, actor, amount: int):
world.hello[actor] = world.hello.get(actor, 0) + amount
return {'actor': actor, 'count': world.hello[actor]}
@staticmethod
def _total(world, actor):
return {'count': sum(world.hello.values())}
工具签名怎么写
工具函数的第二个参数永远是行动者,其余参数从 schema 自动推导:
def _add(world, actor, amount: int): ... # amount 是整数
def _move(world, actor, x: int, y: int): ... # 两个整数
def _note(world, actor, text: str = ''): ... # 带默认值 → 可选
类型标注会变成 JSON Schema 的 type;要更细的约束(枚举、最小值、是否必填)就手写 parameters:
Tool('build', self._build,
parameters={'type': 'object', 'properties': {
'x': {'type': 'integer', 'minimum': 0},
'kind': {'type': 'string', 'enum': ['farm', 'mine']}},
'required': ['x', 'kind'], 'additionalProperties': False},
description='……')
装载期的硬性检查
装载时引擎会核对声明与实现是否一致,不一致直接拒绝装载,不会静默兜底:
| 检查 | 例子 |
|---|---|
Provides 与实现的能力对得上 | 声明了 example:hello 却没有 objects() 里给这个能力 → 拒绝 |
| 声明的依赖存在 | Requires 指向不存在的模块 → 拒绝 |
| 能力名不重复 | 两个模块提供同名能力 → 拒绝 |
| 状态键不重复拥有 | 两个模块 Owns 同一个键 → 拒绝 |
| 工具名唯一 | 两个工具同名 → 拒绝 |
PlayerState 里的工具存在且只读 | 写了一个不存在的工具名 → 拒绝 |
Interfaces 里的方法真存在 | 调了对方没有的方法 → 拒绝 |
报错信息一般直接指出是哪一条,见报错速查。
装起来试
from engine.runtime import Runtime, Unit
from mods.examples.hello.mod import HelloMod
# 进程内装载:不落发行版清单,适合单模块开发
runtime = Runtime([Unit('example:hello', HelloMod(), version='1.0.0')])
world = runtime.world_class()()
print(runtime.call(world, 'demo', 'hello_add', {'amount': 3}))
把模块目录直接给 Runtime.load 也可以(目录里只有 mod.toml 没有发行版清单时, 引擎会按目录名自动装成一个发行版)。