Screeps - 按范围1来过滤容器(容器采矿)

时间:2017-04-20 08:04:36

标签: javascript screeps

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

// 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 旁边没有任何消息来源。

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

我不了解循环/迭代,但还没有让这个工作。 我尝试了很多东西但是现在我感到很无助 试图找出这个难题。

1 个答案:

答案 0 :(得分: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
});