1

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

// 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。

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

我还不够了解循环/迭代以使其正常工作。我尝试了很多东西,但现在我试图弄清楚这个谜题感到无助。

4

1 回答 1

1

我认为您可以更新您的第一个过滤器以检查附近的来源,如下所示:

    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
});
于 2017-04-20T19:25:21.593 回答