gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:46:36 25 4
gpt4 key购买 nike

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

// 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
});

关于javascript - Screeps - 按 1 范围内的来源过滤容器(容器挖掘),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43513669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com