Design & Implementation

Creep 模块 —— 设计

🤖️ Creep 模块对外暴露的功能应当是:

  • 申请特定型号的 Creep

  • 归还特定型号的 Creep

  • 设计特定型号的 Creep

🤖️ Creep 模块对内管理的内容应当是:

  • 管理已有的 Creep (申请时的分配、归属房间控制等)

  • 申请生产新的 Creep (数量控制、生的位置选择等)

这样,一个利用 🤖️ Creep 模块的 🔄 流程就是:提前设计好特定型号的 Creep => 进程运行时,动态申请 Creep => Creep 若有,则返回 Id。否则阻塞,直到有相应的 Creep 再唤醒。 => 如果进程运行时错误,则进程释放资源,从头开始;否则运行到结束,释放 Creep。

⚙️ 对外接口依赖

这样的一个 🤖️ Creep 模块,外部的依赖的接口就是 生新的 Creep 了。该函数输入指定房间、生Creep的参数、以及完成后的 callback。callback 的主要作用是返回新生产出来的 Creep Id 到 🤖️ Creep 模块进行管理。

/**
 * 外部接口依赖
 */
interface CreepModuleContext {
    /**
     * 申请生产新的 Creep.
     * 注意: 这个 API 保证成功, 即错误处理应当在 spawn 模块内部.
     *
     * @param roomName 生产 Creep 的房间.
     * @param callback 在 Creep 成功生产后, 执行的回调函数.
     * @param body An array describing the new creep’s body. Should contain 1 to 50 elements with one of these constants:
     *  * WORK
     *  * MOVE
     *  * CARRY
     *  * ATTACK
     *  * RANGED_ATTACK
     *  * HEAL
     *  * TOUGH
     *  * CLAIM
     * @param name The name of a new creep. It must be a unique creep name, i.e. the Game.creeps object should not contain another creep with the same name (hash key).
     * @param memory Memory of the new creep. If provided, it will be immediately stored into Memory.creeps[name].
     * @param workPos Creep 预计的工作地点. 可以根据该信息优化生产 Creep 所选用的 Spawn.
     */
    spawnCreep(roomName: string, callback: (id: Id<Creep>) => void, body: BodyPartConstant[], name: string, memory?: CreepMemory, workPos?: RoomPosition): void
}

☠️ Creep 消亡处理

对称的,除了新生产的 Creep 加入到 🤖️ Creep 模块 中进行管理之外,我们也还要处理旧的 Creep 的消亡。一种做法是每 tick 刚开始,都检查是否有 Creep 消亡,消亡的话,取消管理并释放资源。但是其实我们可以 Lazy 一些,就是只有在需要特定型号的 Creep 的时候,去检查目前管理的 Creep 存不存在;不存在,再执行消亡。除此之外,我们还可以定期 (例如 1500 ticks) 的清除一下死亡的 Creep 的 Memory,防止有些型号一直没有申请,然后以前的占用的资源得不到释放。

📃 具体实现

triangle-exclamation

Last updated