pyxen.world.all()
按组件查询实体。
world.all(*components, without=None)
返回所有匹配查询的实体的迭代器。
这是 Pyxen ECS 系统的核心。
基本用法
for e in world.all("enemy"):
e.health.value -= 1
这会遍历所有拥有 "enemy" 组件的实体。
组件通过**名称(字符串)**来标识。
多个组件
你可以要求多个组件:
for e in world.all("position", "velocity"):
e.position.x += e.velocity.x
这只返回同时拥有两个组件的实体。
可以理解为:
AND 查询
排除组件(without)
你可以使用 without 关键字排除拥有特定组件的实体。
for e in world.all("enemy", without=("dead",)):
attack(e)
这意味着:
- 必须拥有
"enemy" - 必须没有
"dead"
完整语法
world.all(
"required_component_1",
"required_component_2",
...,
without=("excluded_component_1", "excluded_component_2")
)
- 必需组件是位置参数
without必须是元组
示例:生命游戏
for cell in world.all("cell"):
if cell.alive and cell.next_alive:
cell.color = (0.25, 0.15, 0.85, 1.0)
示例:仅活着的细胞
for cell in world.all("cell", without=("dead",)):
update(cell)
标记组件与查询
标记组件(仅布尔值的组件)的工作方式完全相同。
e.enemy = True
然后:
for e in world.all("enemy"):
...
标记在查询中非常高效。
内置组件与查询
你可以按内置组件查询实体:
for e in world.all("sprite"):
e.color = (1, 0, 0, 1)
支持以下内置组件名称:
| 名称 | 匹配的实体 |
|---|---|
"sprite" | 拥有精灵(已分配图像) |
"body" | 拥有网格体(碰撞体) |
"camera" | 拥有摄像机 |
"sound" | 拥有音效 |
"music" | 拥有音乐流 |
"map" | 拥有网格地图(瓦片地图) |
你可以在同一查询中混合使用内置和自定义组件:
for e in world.all("sprite", "enemy"):
e.color = (1, 0, 0, 1)
排除同样有效:
for e in world.all("sprite", without=("body",)):
...
查询行为
内部流程:
- 查询收集所需的组件模式
- 收集排除的组件模式
- 遍历匹配的实体
- 产出
Entity句柄
如果组件名称不存在:
- 记录警告
- 查询仍然继续
重要注意事项
组件名称必须是字符串
world.all("health")
正确。
world.all(health)
错误。
without 必须是元组
world.all("enemy", without=("dead",))
正确。
world.all("enemy", without="dead")
错误。
返回值
world.all() 返回一个迭代器。
你可以:
list(world.all("enemy"))
或:
for e in world.all("enemy"):
...
安全说明
如果所需的组件不存在:
- 记录警告
- 查询继续
如果传入过多组件,引擎的内部上限会生效。