Screeps - 按 1 范围内的来源过滤容器(容器挖掘)

Screeps - filter containers by sources in range of 1 (container mining)

实际上我想找到旁边没有资源的容器, 这样我的卡车就可以更灵活地在基地周围传输能量 而不是拥有一个巨大的存储空间。 (我的控制器很远)

// find all containers in room
var containers = creep.room.find(FIND_STRUCTURES, {
    filter: (s) => s.structureType == STRUCTURE_CONTAINER
});
// find all sources
var sources = creep.room.find(FIND_SOURCES);
// if there is no source next to the container
if (!(sources.length < 0)) {
}

这完成没有错误,但我无法设法获取容器 ID 旁边没有来源。

我相信我必须在过滤器中包含逻辑,很可能循环遍历每个容器?

我对循环/迭代的理解还不够,无法使它正常工作。 我尝试了很多事情,但现在我感到无助 试图找出这个谜题。

我认为您可以像这样更新您的第一个过滤器来检查附近的来源:

    let containers = creep.room.find(FIND_STRUCTURES, {
        filter: (s) => s.structureType === STRUCTURE_CONTAINER && s.pos.findInRange(FIND_SOURCES, 2).length === 0
    });

我使用 2 作为范围,但如果你的容器总是与你的源相邻(或很远),你可以将其更改为 1。

如果将结果存储在内存中,您将节省 CPU。如果你想知道如何做到这一点,我可以提供更多信息。

编辑:对于缓存,您可以像这样在 Room 对象上创建一个 属性(可能需要对此进行一些调试 - 我写了但没有测试):

Object.defineProperty(Room.prototype, 'nonSourceContainers', {
    get: function () {
        if (this === Room.prototype || this === undefined) return undefined;

        const room = this;

        // If any containers have been constructed that don't have isNearSource defined, fix that first.
        let newContainers = room.find(FIND_STRUCTURES, {
            filter: (s) => s.structureType === STRUCTURE_CONTAINER && s.memory.isNearSource === undefined
        });

        // Found some new containers?
        if (newContainers.length) {
            for (let i = 0; i < newContainers.length; ++i) {
                newContainers[i].memory.isNearSource = newContainers[i].pos.findInRange(FIND_SOURCES, 2).length > 0;
            }

            // Set the list of non-source container ids in the room's memory. This lasts forever.
            room.memory.nonSourceContainerIds = room.find(FIND_STRUCTURES, {filter: {isNearSource: false}});

            // Reset the cached set of containers.
            room._nonSourceContainers = undefined;
        }

        // If there is no cached list, create it. Caching will mean the following runs once per tick or less.
        if (!room._nonSourceContainers) {
            if (!room.memory.nonSourceContainerIds) {
                room.memory.nonSourceContainerIds = [];
            }

            // Get the containers by their ids.
            room._nonSourceContainers = room.memory.nonSourceContainerIds.map(id => Game.getObjectById(id));
        }

        return room._nonSourceContainers;
    },
    enumerable: false,
    configurable: true
});